@openclaw/matrix 2026.9.2 → 2026.9.4

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 (68) hide show
  1. package/dist/{account-selection-DA-jfx22.js → account-selection-Bbtc483D.js} +9 -1
  2. package/dist/{accounts-DR1c4xF_.js → accounts-GwSAk9vY.js} +2 -2
  3. package/dist/api.js +6 -6
  4. package/dist/{approval-handler.runtime-BJCD4dLf.js → approval-handler.runtime-6I3IpyeX.js} +6 -6
  5. package/dist/{approval-ids-Bst7HM_o.js → approval-ids-C4NdeXNz.js} +1 -1
  6. package/dist/{approval-reaction-auth-DhH8QOSe.js → approval-reaction-auth-cbltZAUQ.js} +2 -2
  7. package/dist/{channel-Bs8VLb6q.js → channel-Cg97H4c1.js} +13 -202
  8. package/dist/channel-plugin-api.js +1 -1
  9. package/dist/{channel.runtime-CCJRhdH5.js → channel.runtime-Bhpfa1qc.js} +6 -11
  10. package/dist/{channel.setup-DhmDXwPp.js → channel.setup-DmS7m7aT.js} +3 -3
  11. package/dist/{cli-IvDUuiDH.js → cli-CLexRrQw.js} +9 -9
  12. package/dist/{cli-metadata-BGryAl2e.js → cli-metadata-zRyVmUOL.js} +1 -1
  13. package/dist/cli-metadata.js +1 -1
  14. package/dist/{client-oNOlldJI.js → client-C0nZFCTj.js} +2 -2
  15. package/dist/{client-Dj4mcf-s.js → client-CPcRv6ab.js} +6 -6
  16. package/dist/{client-bootstrap-n1Rqc8Go.js → client-bootstrap-DLN-K8Xb.js} +1 -6
  17. package/dist/contract-api.js +2 -2
  18. package/dist/{credentials-DJj2xs3q.js → credentials-DysXbkv2.js} +2 -2
  19. package/dist/{credentials-read-mexhw-Ur.js → credentials-read-WWpqi88V.js} +1 -1
  20. package/dist/{credentials-write.runtime-DQt-kgJq.js → credentials-write.runtime-D22lPwRO.js} +1 -1
  21. package/dist/{crypto-runtime-m1eplj3b.js → crypto-runtime-DiyH4R3D.js} +3 -25
  22. package/dist/{crypto-snapshot-doctor.runtime-D0v841D_.js → crypto-snapshot-doctor.runtime-DxgUMXUy.js} +2 -2
  23. package/dist/{directory-live-DLUgWBhA.js → directory-live-B8-GAVcc.js} +2 -2
  24. package/dist/doctor-contract-api.js +41 -21
  25. package/dist/{draft-stream-DglwxWzJ.js → draft-stream--NdEtnZ8.js} +16 -5
  26. package/dist/{encryption-guidance-BNcZNQZI.js → encryption-guidance-mDyxJV9U.js} +1 -1
  27. package/dist/{event-helpers-XRfAbOIh.js → event-helpers-CspuhE9k.js} +9 -1
  28. package/dist/helper-api.js +3 -3
  29. package/dist/{http-client-DOmFvKvB.js → http-client-BfPeF4CE.js} +1 -1
  30. package/dist/{idb-persistence-CU7CNLlX.js → idb-persistence-DBdwHSWg.js} +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/{messages-Czn8lNEh.js → messages-CpZfiQO0.js} +6 -99
  33. package/dist/{monitor-DouG43FJ.js → monitor-BUek91SW.js} +61 -92
  34. package/dist/{outbound-Co_tJyE6.js → outbound-D91JinYa.js} +1 -1
  35. package/dist/plugin-entry.handlers.runtime.js +1 -1
  36. package/dist/probe.runtime-DWdw74_H.js +2 -0
  37. package/dist/{profile-update-CAl8nZNG.js → profile-update-vnhxwjEt.js} +1 -1
  38. package/dist/{reaction-events-C_7G7bvI.js → reaction-events-2WM2nJe_.js} +5 -7
  39. package/dist/{resolve-targets-B64O69Nd.js → resolve-targets-K8D0HWPX.js} +1 -1
  40. package/dist/{resolver.runtime-TRmePJDV.js → resolver.runtime-C88GwQCx.js} +1 -1
  41. package/dist/{room-info-6viLR3NH.js → room-info-BPVJkXnp.js} +7 -4
  42. package/dist/runtime-api.js +2 -2
  43. package/dist/{sdk-C1yfda1L.js → sdk-B4By16Bt.js} +13 -6
  44. package/dist/{send-B5XChnvB.js → send-UWLIQ0bG.js} +211 -135
  45. package/dist/session-binding-contract-api.js +1 -1
  46. package/dist/{setup-bootstrap-S_loyUyM.js → setup-bootstrap-sVqkwtSY.js} +2 -2
  47. package/dist/{setup-core-XkIfQ65J.js → setup-core-8keb-Yre.js} +14 -29
  48. package/dist/setup-plugin-api.js +1 -1
  49. package/dist/{setup-surface-B2yZ8KGc.js → setup-surface-bcluelBI.js} +8 -17
  50. package/dist/{startup-verification-1Ney1mmI.js → startup-verification-BTSf31hS.js} +2 -1
  51. package/dist/storage-CV-pfV_2.js +320 -0
  52. package/dist/{storage-BVf4uucD.js → storage-metadata-DYArLcq1.js} +14 -319
  53. package/dist/{storage-paths-gUmSydsW.js → storage-paths-DVCANXTc.js} +13 -1
  54. package/dist/{sync-cache-state-d-A_OhbU.js → sync-cache-state-C-mhj3xb.js} +9 -3
  55. package/dist/{thread-bindings-BkBnn4te.js → thread-bindings-Bwv87Gve.js} +3 -2
  56. package/dist/{tool-actions.runtime-a5L5xGSP.js → tool-actions.runtime-Bf98Juk6.js} +295 -256
  57. package/dist/types-DzSc7Sqm.js +32 -0
  58. package/dist/{verification-XJtTc5DI.js → verification-BbG-VC9S.js} +2 -2
  59. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/package.json +1 -1
  60. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm.d.ts +69 -4
  61. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.cjs +526 -432
  62. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.js +358 -265
  63. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm +0 -0
  64. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm.d.ts +8 -7
  65. package/openclaw.plugin.json +27 -1
  66. package/package.json +5 -5
  67. package/dist/probe.runtime-B1YPxG9x.js +0 -2
  68. package/dist/runtime-BefyhPWv.js +0 -6
@@ -1,15 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { n as requiresExplicitMatrixDefaultAccount, s as resolveMatrixEnvAuthReadiness } from "./account-selection-DA-jfx22.js";
2
+ import { c as resolveMatrixEnvAuthReadiness, r as requiresExplicitMatrixDefaultAccount } from "./account-selection-Bbtc483D.js";
3
3
  import { a as resolveMatrixAccountConfig } from "./account-config-CRsKoMqJ.js";
4
- import { i as resolveMatrixAccount, r as resolveDefaultMatrixAccountId, t as listMatrixAccountIds } from "./accounts-DR1c4xF_.js";
4
+ import { i as resolveMatrixAccount, r as resolveDefaultMatrixAccountId, t as listMatrixAccountIds } from "./accounts-GwSAk9vY.js";
5
5
  import { n as isMatrixRoomId } from "./target-ids-Nwx7cMVE.js";
6
6
  import { r as updateMatrixAccountConfig } from "./config-update-BnX26jCO.js";
7
- import { a as moveSingleMatrixAccountConfigToNamedAccount, i as createMatrixSetupDmPolicy } from "./setup-core-XkIfQ65J.js";
7
+ import { a as moveSingleMatrixAccountConfigToNamedAccount, i as createMatrixSetupDmPolicy } from "./setup-core-8keb-Yre.js";
8
8
  import { n as validateMatrixHomeserverUrl, r as isPrivateOrLoopbackHost, t as resolveValidatedMatrixHomeserverUrl } from "./url-validation-GRHde6lq.js";
9
9
  import { n as ensureMatrixSdkInstalled, r as isMatrixSdkAvailable } from "./deps-mtxF2mHI.js";
10
10
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringifiedOptionalString, normalizeUniqueStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
11
11
  import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-id";
12
- import { formatDocsLink, hasConfiguredSecretInput, mergeAllowFromEntries, normalizeAccountId as normalizeAccountId$1, promptAccountId, promptChannelAccessConfig, splitSetupEntries } from "openclaw/plugin-sdk/setup";
12
+ import { formatDocsLink, hasConfiguredSecretInput, mergeAllowFromEntries, normalizeAccountId as normalizeAccountId$1, promptAccountId, promptChannelAccessConfig, setSetupChannelEnabled, splitSetupEntries } from "openclaw/plugin-sdk/setup";
13
13
  import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-policy";
14
14
  //#region extensions/matrix/src/onboarding.ts
15
15
  const channel = "matrix";
@@ -91,7 +91,7 @@ async function promptMatrixAllowFrom(params) {
91
91
  pending.push(part);
92
92
  }
93
93
  if (pending.length > 0) {
94
- const { resolveMatrixTargets } = await import("./resolve-targets-B64O69Nd.js").then((n) => n.n);
94
+ const { resolveMatrixTargets } = await import("./resolve-targets-K8D0HWPX.js").then((n) => n.n);
95
95
  const results = await resolveMatrixTargets({
96
96
  cfg,
97
97
  accountId,
@@ -211,7 +211,7 @@ async function configureMatrixAccessPrompts(params) {
211
211
  resolvedIds.push(cleaned);
212
212
  continue;
213
213
  }
214
- const { listMatrixDirectoryGroupsLive } = await import("./directory-live-DLUgWBhA.js").then((n) => n.t);
214
+ const { listMatrixDirectoryGroupsLive } = await import("./directory-live-B8-GAVcc.js").then((n) => n.t);
215
215
  const matches = await listMatrixDirectoryGroupsLive({
216
216
  cfg: next,
217
217
  accountId: params.accountId,
@@ -464,7 +464,7 @@ const matrixOnboardingAdapter = {
464
464
  });
465
465
  },
466
466
  afterConfigWritten: async ({ previousCfg, cfg, accountId, runtime }) => {
467
- const { runMatrixSetupBootstrapAfterConfigWrite } = await import("./setup-bootstrap-S_loyUyM.js");
467
+ const { runMatrixSetupBootstrapAfterConfigWrite } = await import("./setup-bootstrap-sVqkwtSY.js");
468
468
  await runMatrixSetupBootstrapAfterConfigWrite({
469
469
  previousCfg,
470
470
  cfg,
@@ -473,16 +473,7 @@ const matrixOnboardingAdapter = {
473
473
  });
474
474
  },
475
475
  dmPolicy,
476
- disable: (cfg) => ({
477
- ...cfg,
478
- channels: {
479
- ...cfg.channels,
480
- matrix: {
481
- ...cfg.channels?.["matrix"],
482
- enabled: false
483
- }
484
- }
485
- })
476
+ disable: (cfg) => setSetupChannelEnabled(cfg, channel, false)
486
477
  };
487
478
  //#endregion
488
479
  //#region extensions/matrix/src/setup-surface.ts
@@ -1,5 +1,6 @@
1
1
  import { t as getMatrixRuntime } from "./runtime-6S3DNFNv.js";
2
- import { M as resolveMatrixSqliteStateEnv, l as resolveMatrixStoragePaths, o as recordCurrentStorageMetaDeviceId } from "./storage-BVf4uucD.js";
2
+ import { k as resolveMatrixSqliteStateEnv } from "./storage-metadata-DYArLcq1.js";
3
+ import { o as resolveMatrixStoragePaths, r as recordCurrentStorageMetaDeviceId } from "./storage-CV-pfV_2.js";
3
4
  import { createHash } from "node:crypto";
4
5
  import path from "node:path";
5
6
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
@@ -0,0 +1,320 @@
1
+ import { t as getMatrixRuntime } from "./runtime-6S3DNFNv.js";
2
+ import { n as isMatrixActiveTokenRootDirectory, r as resolveMatrixAccountStorageRoot } from "./storage-paths-DVCANXTc.js";
3
+ import { C as scoreMatrixCryptoStateInStore, c as MATRIX_RECOVERY_KEY_FILENAME, d as migrateLegacyMatrixLegacyCryptoMigrationFileToStore, i as openMatrixStorageMetaStoreOptions, o as MATRIX_IDB_SNAPSHOT_FILENAME, p as migrateLegacyMatrixRecoveryKeyFileToStore, r as normalizeMatrixStorageMetadata, s as MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME, t as STORAGE_META_STATE_KEY } from "./storage-metadata-DYArLcq1.js";
4
+ import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ import { loadJsonFile } from "openclaw/plugin-sdk/json-store";
8
+ import os from "node:os";
9
+ //#region extensions/matrix/src/matrix/client/storage.ts
10
+ const DEFAULT_ACCOUNT_KEY = "default";
11
+ const STORAGE_META_FILENAME = "storage-meta.json";
12
+ const THREAD_BINDINGS_FILENAME = "thread-bindings.json";
13
+ function openStorageMetaStore(rootDir) {
14
+ return getMatrixRuntime().state.openSyncKeyedStore(openMatrixStorageMetaStoreOptions(rootDir));
15
+ }
16
+ function scoreStorageRoot(rootDir, metadata = readStoredRootMetadata(rootDir)) {
17
+ let score = 0;
18
+ if (Object.keys(metadata).length > 0) score += 1;
19
+ if (metadata.currentTokenStateClaimed === true) score += 8;
20
+ if (fs.existsSync(path.join(rootDir, "crypto"))) score += 8;
21
+ if (fs.existsSync(path.join(rootDir, THREAD_BINDINGS_FILENAME))) score += 4;
22
+ if (fs.existsSync(path.join(rootDir, "legacy-crypto-migration.json"))) score += 3;
23
+ if (fs.existsSync(path.join(rootDir, "recovery-key.json"))) score += 2;
24
+ if (fs.existsSync(path.join(rootDir, "crypto-idb-snapshot.json"))) score += 2;
25
+ score += scoreMatrixCryptoStateInStore(rootDir);
26
+ return score;
27
+ }
28
+ function resolveStorageRootMtimeMs(rootDir) {
29
+ try {
30
+ return fs.statSync(rootDir).mtimeMs;
31
+ } catch {
32
+ return 0;
33
+ }
34
+ }
35
+ function readStoredRootMetadata(rootDir) {
36
+ if (fs.existsSync(path.join(rootDir, "state", "openclaw.sqlite"))) try {
37
+ const stored = normalizeMatrixStorageMetadata(openStorageMetaStore(rootDir).lookup(STORAGE_META_STATE_KEY));
38
+ if (stored) return stored;
39
+ } catch {}
40
+ return normalizeMatrixStorageMetadata(loadJsonFile(path.join(rootDir, STORAGE_META_FILENAME))) ?? {};
41
+ }
42
+ function isCompatibleStorageRoot(params) {
43
+ const metadata = readStoredRootMetadata(params.candidateRootDir);
44
+ if (metadata.homeserver && metadata.homeserver !== params.homeserver) return false;
45
+ if (metadata.userId && metadata.userId !== params.userId) return false;
46
+ if (metadata.accountId && normalizeAccountId(metadata.accountId) !== normalizeAccountId(params.accountKey)) return false;
47
+ if (params.deviceId && metadata.deviceId && metadata.deviceId.trim() && metadata.deviceId.trim() !== params.deviceId.trim()) return false;
48
+ if (params.requireExplicitDeviceMatch && params.deviceId && (!metadata.deviceId || metadata.deviceId.trim() !== params.deviceId.trim())) return false;
49
+ return true;
50
+ }
51
+ function resolvePreferredMatrixStorageRoot(params) {
52
+ const canonical = {
53
+ rootDir: params.canonicalRootDir,
54
+ tokenHash: params.canonicalTokenHash
55
+ };
56
+ const deviceId = params.deviceId?.trim();
57
+ if (!deviceId) return canonical;
58
+ const canonicalMetadata = readStoredRootMetadata(params.canonicalRootDir);
59
+ if (canonicalMetadata.accessTokenHash === params.canonicalTokenHash && canonicalMetadata.deviceId?.trim() === deviceId && canonicalMetadata.currentTokenStateClaimed === true) return canonical;
60
+ const parentDir = path.dirname(params.canonicalRootDir);
61
+ const bestCurrentScore = scoreStorageRoot(params.canonicalRootDir, canonicalMetadata);
62
+ const bestCurrentMtimeMs = resolveStorageRootMtimeMs(params.canonicalRootDir);
63
+ let best = {
64
+ rootDir: params.canonicalRootDir,
65
+ tokenHash: params.canonicalTokenHash,
66
+ score: bestCurrentScore,
67
+ mtimeMs: bestCurrentMtimeMs
68
+ };
69
+ let siblingEntries;
70
+ try {
71
+ siblingEntries = fs.readdirSync(parentDir, { withFileTypes: true });
72
+ } catch {
73
+ return {
74
+ rootDir: best.rootDir,
75
+ tokenHash: best.tokenHash
76
+ };
77
+ }
78
+ const compatiblePopulatedSiblings = [];
79
+ const populatedTokenHashes = bestCurrentScore > 0 ? [params.canonicalTokenHash] : [];
80
+ for (const entry of siblingEntries.toSorted((a, b) => a.name.localeCompare(b.name))) {
81
+ if (!entry.isDirectory()) continue;
82
+ if (entry.name === params.canonicalTokenHash) continue;
83
+ if (!isMatrixActiveTokenRootDirectory(entry.name)) continue;
84
+ const candidateRootDir = path.join(parentDir, entry.name);
85
+ if (!isCompatibleStorageRoot({
86
+ candidateRootDir,
87
+ homeserver: params.homeserver,
88
+ userId: params.userId,
89
+ accountKey: params.accountKey,
90
+ deviceId,
91
+ requireExplicitDeviceMatch: true
92
+ })) continue;
93
+ const candidateScore = scoreStorageRoot(candidateRootDir);
94
+ if (candidateScore <= 0) continue;
95
+ populatedTokenHashes.push(entry.name);
96
+ compatiblePopulatedSiblings.push({
97
+ rootDir: candidateRootDir,
98
+ tokenHash: entry.name,
99
+ score: candidateScore,
100
+ mtimeMs: resolveStorageRootMtimeMs(candidateRootDir)
101
+ });
102
+ }
103
+ for (const candidate of compatiblePopulatedSiblings) if (candidate.score > best.score || best.rootDir !== params.canonicalRootDir && candidate.score === best.score && candidate.mtimeMs > best.mtimeMs) best = {
104
+ rootDir: candidate.rootDir,
105
+ tokenHash: candidate.tokenHash,
106
+ score: candidate.score,
107
+ mtimeMs: candidate.mtimeMs
108
+ };
109
+ if (populatedTokenHashes.length > 1) getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" }).warn("matrix: multiple populated token-hash storage roots detected", {
110
+ parentDir,
111
+ canonicalTokenHash: params.canonicalTokenHash,
112
+ selectedTokenHash: best.tokenHash,
113
+ populatedTokenHashes,
114
+ populatedSiblingTokenHashes: compatiblePopulatedSiblings.map((root) => root.tokenHash),
115
+ populatedRootCount: populatedTokenHashes.length
116
+ });
117
+ return {
118
+ rootDir: best.rootDir,
119
+ tokenHash: best.tokenHash
120
+ };
121
+ }
122
+ function resolveMatrixStoragePaths(params) {
123
+ const env = params.env ?? process.env;
124
+ const stateDir = params.stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir);
125
+ const canonical = resolveMatrixAccountStorageRoot({
126
+ stateDir,
127
+ homeserver: params.homeserver,
128
+ userId: params.userId,
129
+ accessToken: params.accessToken,
130
+ accountId: params.accountId
131
+ });
132
+ const { rootDir, tokenHash } = resolvePreferredMatrixStorageRoot({
133
+ canonicalRootDir: canonical.rootDir,
134
+ canonicalTokenHash: canonical.tokenHash,
135
+ homeserver: params.homeserver,
136
+ userId: params.userId,
137
+ accountKey: canonical.accountKey,
138
+ deviceId: params.deviceId
139
+ });
140
+ return {
141
+ rootDir,
142
+ storagePath: path.join(rootDir, "bot-storage.json"),
143
+ cryptoPath: path.join(rootDir, "crypto"),
144
+ recoveryKeyPath: path.join(rootDir, MATRIX_RECOVERY_KEY_FILENAME),
145
+ idbSnapshotPath: path.join(rootDir, MATRIX_IDB_SNAPSHOT_FILENAME),
146
+ accountKey: canonical.accountKey,
147
+ tokenHash
148
+ };
149
+ }
150
+ function resolveMatrixStateFilePath(params) {
151
+ const storagePaths = resolveMatrixStoragePaths({
152
+ homeserver: params.auth.homeserver,
153
+ userId: params.auth.userId,
154
+ accessToken: params.auth.accessToken,
155
+ accountId: params.accountId ?? params.auth.accountId,
156
+ deviceId: params.auth.deviceId,
157
+ env: params.env,
158
+ stateDir: params.stateDir
159
+ });
160
+ return path.join(storagePaths.rootDir, params.filename);
161
+ }
162
+ async function maybeMigrateLegacyStorage(params) {
163
+ const hasAccountScopedLegacyStorageFile = fs.existsSync(params.storagePaths.storagePath);
164
+ const syncCache = hasAccountScopedLegacyStorageFile ? await import("./sync-cache-state-C-mhj3xb.js").then((n) => n.s) : null;
165
+ const hasAccountScopedLegacyStorage = hasAccountScopedLegacyStorageFile && await syncCache?.readLegacyMatrixSyncCacheState(params.storagePaths.rootDir) !== null;
166
+ const hasAccountScopedRecoveryKey = fs.existsSync(params.storagePaths.recoveryKeyPath);
167
+ const hasAccountScopedLegacyCryptoMigration = fs.existsSync(path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME));
168
+ if (!hasAccountScopedLegacyStorage && !hasAccountScopedRecoveryKey && !hasAccountScopedLegacyCryptoMigration) return;
169
+ const logger = getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" });
170
+ fs.mkdirSync(params.storagePaths.rootDir, { recursive: true });
171
+ const moved = [];
172
+ const pendingArchives = [];
173
+ const skippedExistingTargets = [];
174
+ try {
175
+ if (hasAccountScopedLegacyStorage) await migrateLegacySyncCacheToSqlite({
176
+ sourceRootDir: params.storagePaths.rootDir,
177
+ sourcePath: params.storagePaths.storagePath,
178
+ targetRootDir: params.storagePaths.rootDir,
179
+ label: "account sync cache",
180
+ moved,
181
+ pendingArchives
182
+ });
183
+ if (hasAccountScopedRecoveryKey) {
184
+ migrateLegacyMatrixRecoveryKeyFileToStore(params.storagePaths.rootDir);
185
+ moved.push({
186
+ sourcePath: params.storagePaths.recoveryKeyPath,
187
+ targetPath: `${params.storagePaths.rootDir} SQLite recovery key state`,
188
+ label: "recovery key"
189
+ });
190
+ }
191
+ if (hasAccountScopedLegacyCryptoMigration) {
192
+ migrateLegacyMatrixLegacyCryptoMigrationFileToStore(params.storagePaths.rootDir);
193
+ moved.push({
194
+ sourcePath: path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME),
195
+ targetPath: `${params.storagePaths.rootDir} SQLite legacy crypto migration state`,
196
+ label: "legacy crypto migration"
197
+ });
198
+ }
199
+ } catch (err) {
200
+ const rollbackError = rollbackLegacyMoves(moved);
201
+ throw new Error(rollbackError ? `Failed migrating legacy Matrix client storage: ${String(err)}. Rollback also failed: ${rollbackError}` : `Failed migrating legacy Matrix client storage: ${String(err)}`, { cause: err });
202
+ }
203
+ for (const archive of pendingArchives) archiveLegacyStoragePath({
204
+ ...archive,
205
+ skippedExistingTargets
206
+ });
207
+ if (moved.length > 0) logger.info(`matrix: migrated legacy client storage into ${params.storagePaths.rootDir}\n${moved.map((entry) => `- ${entry.label}: ${entry.sourcePath} -> ${entry.targetPath}`).join("\n")}`);
208
+ if (skippedExistingTargets.length > 0) logger.warn?.(`matrix: legacy client storage files were left in place because their migrated targets already existed.\n${skippedExistingTargets.join("\n")}`);
209
+ }
210
+ async function migrateLegacySyncCacheToSqlite(params) {
211
+ const syncCache = await import("./sync-cache-state-C-mhj3xb.js").then((n) => n.s);
212
+ const persisted = await syncCache.readLegacyMatrixSyncCacheState(params.sourceRootDir);
213
+ if (!persisted) return;
214
+ const store = getMatrixRuntime().state.openKeyedStore(syncCache.openMatrixSyncCacheStoreOptions(params.targetRootDir));
215
+ if (!await syncCache.hasMatrixSyncCacheStateInStore({
216
+ storageRootDir: params.targetRootDir,
217
+ store
218
+ })) {
219
+ await syncCache.writeMatrixSyncCacheStateToStore({
220
+ storageRootDir: params.targetRootDir,
221
+ payload: persisted,
222
+ store
223
+ });
224
+ claimCurrentTokenStorageState({ rootDir: params.targetRootDir });
225
+ params.moved.push({
226
+ sourcePath: params.sourcePath,
227
+ targetPath: `${params.targetRootDir} SQLite sync cache`,
228
+ label: params.label
229
+ });
230
+ }
231
+ params.pendingArchives.push({
232
+ sourcePath: params.sourcePath,
233
+ label: params.label
234
+ });
235
+ }
236
+ function archiveLegacyStoragePath(params) {
237
+ const archivedLegacyStoragePath = `${params.sourcePath}.migrated`;
238
+ if (fs.existsSync(archivedLegacyStoragePath)) {
239
+ params.skippedExistingTargets.push(`- ${params.label} remains at ${params.sourcePath} because ${archivedLegacyStoragePath} already exists`);
240
+ return;
241
+ }
242
+ fs.renameSync(params.sourcePath, archivedLegacyStoragePath);
243
+ }
244
+ function rollbackLegacyMoves(moved) {
245
+ for (const entry of moved.toReversed()) try {
246
+ if (!fs.existsSync(entry.targetPath) || fs.existsSync(entry.sourcePath)) continue;
247
+ fs.renameSync(entry.targetPath, entry.sourcePath);
248
+ } catch (err) {
249
+ return `${entry.label} (${entry.targetPath} -> ${entry.sourcePath}): ${String(err)}`;
250
+ }
251
+ return null;
252
+ }
253
+ function writeStoredRootMetadata(rootDir, payload) {
254
+ try {
255
+ const normalized = normalizeMatrixStorageMetadata(payload);
256
+ if (!normalized) return false;
257
+ openStorageMetaStore(rootDir).register(STORAGE_META_STATE_KEY, normalized);
258
+ return true;
259
+ } catch {
260
+ return false;
261
+ }
262
+ }
263
+ function writeStorageMeta(params) {
264
+ const existing = readStoredRootMetadata(params.storagePaths.rootDir);
265
+ return writeStoredRootMetadata(params.storagePaths.rootDir, {
266
+ homeserver: params.homeserver,
267
+ userId: params.userId,
268
+ accountId: params.accountId ?? DEFAULT_ACCOUNT_KEY,
269
+ accessTokenHash: params.storagePaths.tokenHash,
270
+ deviceId: params.deviceId ?? null,
271
+ currentTokenStateClaimed: params.currentTokenStateClaimed ?? existing.currentTokenStateClaimed === true,
272
+ createdAt: existing.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
273
+ });
274
+ }
275
+ function claimCurrentTokenStorageState(params) {
276
+ const metadata = readStoredRootMetadata(params.rootDir);
277
+ if (!metadata.accessTokenHash?.trim()) return false;
278
+ return writeStoredRootMetadata(params.rootDir, {
279
+ homeserver: metadata.homeserver,
280
+ userId: metadata.userId,
281
+ accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
282
+ accessTokenHash: metadata.accessTokenHash,
283
+ deviceId: metadata.deviceId ?? null,
284
+ currentTokenStateClaimed: true,
285
+ createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
286
+ });
287
+ }
288
+ function recordCurrentStorageMetaDeviceId(params) {
289
+ const deviceId = params.deviceId.trim();
290
+ if (!deviceId) return false;
291
+ const metadata = readStoredRootMetadata(params.rootDir);
292
+ if (!metadata.accessTokenHash?.trim()) return false;
293
+ return writeStoredRootMetadata(params.rootDir, {
294
+ homeserver: metadata.homeserver,
295
+ userId: metadata.userId,
296
+ accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
297
+ accessTokenHash: metadata.accessTokenHash,
298
+ deviceId,
299
+ currentTokenStateClaimed: metadata.currentTokenStateClaimed === true,
300
+ createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
301
+ });
302
+ }
303
+ function repairCurrentTokenStorageMetaDeviceId(params) {
304
+ return writeStorageMeta({
305
+ storagePaths: resolveMatrixStoragePaths({
306
+ homeserver: params.homeserver,
307
+ userId: params.userId,
308
+ accessToken: params.accessToken,
309
+ accountId: params.accountId,
310
+ env: params.env,
311
+ stateDir: params.stateDir
312
+ }),
313
+ homeserver: params.homeserver,
314
+ userId: params.userId,
315
+ accountId: params.accountId,
316
+ deviceId: params.deviceId
317
+ });
318
+ }
319
+ //#endregion
320
+ export { resolveMatrixStateFilePath as a, repairCurrentTokenStorageMetaDeviceId as i, maybeMigrateLegacyStorage as n, resolveMatrixStoragePaths as o, recordCurrentStorageMetaDeviceId as r, writeStorageMeta as s, claimCurrentTokenStorageState as t };