obsidian-sync-mcp 0.10.0 → 0.12.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.
@@ -2,14 +2,34 @@
2
2
  // Node polyfills for livesync-commonlib browser globals
3
3
  if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
4
  import {
5
- deriveContent
6
- } from "./chunk-GSVMRHWP.js";
5
+ deriveContent,
6
+ resolvePathIdentity
7
+ } from "./chunk-AK3JXN67.js";
7
8
  import {
9
+ AttachmentExistsError,
10
+ AttachmentMoveIncompleteError,
11
+ AttachmentTooLargeError,
8
12
  __reExport,
13
+ isValidAttachmentPath,
9
14
  isValidNotePath,
10
15
  parseFrontmatterAndLinks,
16
+ validateAttachmentPath,
11
17
  validateNotePath
12
- } from "./chunk-VR63UUCB.js";
18
+ } from "./chunk-XZ4HUASL.js";
19
+
20
+ // lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
21
+ import { MemoryValueStore } from "@vrtmrz/value-store";
22
+
23
+ // lib/livesync-commonlib/src/managers/chunkFetchSource.ts
24
+ function createDirectChunkFetchSource(database) {
25
+ return {
26
+ async fetchChunks(ids) {
27
+ const result = await database.allDocs({ keys: ids, include_docs: true });
28
+ return result.rows.flatMap((row) => "doc" in row && row.doc ? [row.doc] : []);
29
+ },
30
+ storeChunks: () => Promise.resolve()
31
+ };
32
+ }
13
33
 
14
34
  // lib/livesync-commonlib/src/common/types.ts
15
35
  import {
@@ -23,6 +43,8 @@ import { RESULT_NOT_FOUND, RESULT_TIMED_OUT } from "octagonal-wheels/common/cons
23
43
 
24
44
  // lib/livesync-commonlib/src/common/models/db.const.ts
25
45
  var VERSIONING_DOCID = "obsydian_livesync_version";
46
+ var MILESTONE_DOCID = "_local/obsydian_livesync_milestone";
47
+ var NODEINFO_DOCID = "_local/obsydian_livesync_nodeinfo";
26
48
  var SYNCINFO_ID = "syncinfo";
27
49
  var EntryTypes = {
28
50
  NOTE_LEGACY: "notes",
@@ -59,7 +81,6 @@ var IDPrefixes = {
59
81
  EncryptedChunk: "h:+"
60
82
  };
61
83
  var PREFIX_OBFUSCATED = "f:";
62
- var PREFIX_ENCRYPTED_CHUNK = "h:+";
63
84
 
64
85
  // lib/livesync-commonlib/src/common/models/setting.const.ts
65
86
  var SETTING_VERSION_INITIAL = 0;
@@ -126,6 +147,7 @@ function normaliseP2PConnectionPath(value) {
126
147
  // lib/livesync-commonlib/src/common/models/setting.const.preferred.ts
127
148
  var PREFERRED_BASE = {
128
149
  syncMaxSizeInMB: 50,
150
+ customChunkSize: 0,
129
151
  chunkSplitterVersion: "v3-rabin-karp",
130
152
  usePluginSyncV2: true,
131
153
  handleFilenameCaseSensitive: false,
@@ -133,21 +155,18 @@ var PREFERRED_BASE = {
133
155
  };
134
156
  var PREFERRED_SETTING_CLOUDANT = {
135
157
  ...PREFERRED_BASE,
136
- customChunkSize: 0,
137
158
  sendChunksBulkMaxSize: 1,
138
159
  concurrencyOfReadChunksOnline: 100,
139
160
  minimumIntervalOfReadChunksOnline: 333
140
161
  };
141
162
  var PREFERRED_SETTING_SELF_HOSTED = {
142
163
  ...PREFERRED_BASE,
143
- customChunkSize: 60,
144
164
  sendChunksBulkMaxSize: 1,
145
165
  concurrencyOfReadChunksOnline: 30,
146
166
  minimumIntervalOfReadChunksOnline: 25
147
167
  };
148
168
  var PREFERRED_JOURNAL_SYNC = {
149
169
  ...PREFERRED_BASE,
150
- customChunkSize: 10,
151
170
  concurrencyOfReadChunksOnline: 30,
152
171
  minimumIntervalOfReadChunksOnline: 25
153
172
  };
@@ -185,8 +204,10 @@ var SETTINGS_SCHEMA_DEFAULTS = {
185
204
  couchDB_PASSWORD: "",
186
205
  couchDB_DBNAME: "",
187
206
  liveSync: false,
207
+ batchSaveInLiveSync: false,
188
208
  syncOnSave: false,
189
209
  syncOnStart: false,
210
+ strictContentCheckOnStartup: false,
190
211
  savingDelay: 200,
191
212
  lessInformationInLog: false,
192
213
  gcDelay: 300,
@@ -200,9 +221,11 @@ var SETTINGS_SCHEMA_DEFAULTS = {
200
221
  periodicReplicationInterval: 60,
201
222
  syncOnFileOpen: false,
202
223
  encrypt: false,
224
+ acceptUnencryptedContent: false,
203
225
  passphrase: "",
204
226
  idDerivationVersion: 0,
205
227
  idDerivationKey: "",
228
+ pathNormalizationVersion: 0,
206
229
  usePathObfuscation: false,
207
230
  encryptInternalMetadata: false,
208
231
  doNotDeleteFolder: false,
@@ -331,6 +354,7 @@ var SETTINGS_SCHEMA_DEFAULTS = {
331
354
  jwtSub: "",
332
355
  jwtExpDuration: 5,
333
356
  useRequestAPI: false,
357
+ useCouchDBCacheControlHeadersOnly: false,
334
358
  bucketPrefix: "",
335
359
  chunkSplitterVersion: ChunkAlgorithms.RabinKarp,
336
360
  E2EEAlgorithm: E2EEAlgorithms.V2,
@@ -357,6 +381,11 @@ function createNewVaultSettings() {
357
381
  }
358
382
  var DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;
359
383
 
384
+ // lib/livesync-commonlib/src/common/models/setting.encryption.ts
385
+ function normaliseAcceptUnencryptedContent(value) {
386
+ return value === true;
387
+ }
388
+
360
389
  // lib/livesync-commonlib/src/common/models/setting.lifecycle.ts
361
390
  var SettingsMigrationReviewCodes = {
362
391
  LegacyUpdatePending: "legacy-update-review-pending",
@@ -426,8 +455,10 @@ function prepareSettingsForLoad(storedSettings) {
426
455
  toVersion: CURRENT_SETTING_VERSION
427
456
  }
428
457
  ];
458
+ const settings = cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS);
459
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(source.acceptUnencryptedContent);
429
460
  return {
430
- settings: cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS),
461
+ settings,
431
462
  sourceVersion,
432
463
  targetVersion: sourceVersion,
433
464
  isNewVault: false,
@@ -461,13 +492,15 @@ function prepareSettingsForLoad(storedSettings) {
461
492
  if (normalisedFilenameCase) migrated = { ...migrated, handleFilenameCaseSensitive: false };
462
493
  const normalisedInternalMetadata = typeof migrated.encryptInternalMetadata !== "boolean";
463
494
  if (normalisedInternalMetadata) migrated = { ...migrated, encryptInternalMetadata: false };
495
+ const normalisedAcceptUnencryptedContent = typeof migrated.acceptUnencryptedContent !== "boolean";
496
+ if (normalisedAcceptUnencryptedContent) migrated = { ...migrated, acceptUnencryptedContent: false };
464
497
  return {
465
498
  settings: cloneSettings(migrated, SETTINGS_SCHEMA_DEFAULTS),
466
499
  sourceVersion,
467
500
  targetVersion,
468
501
  isNewVault: false,
469
502
  isFromFutureSchema: false,
470
- changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata,
503
+ changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata || normalisedAcceptUnencryptedContent,
471
504
  requiresSyncReview: reviewReasons.length > 0,
472
505
  reviewReasons
473
506
  };
@@ -504,6 +537,7 @@ var TweakCompatibilityRules = Object.freeze([
504
537
  { key: "encrypt", templateValue: false, reconstruction: "required" },
505
538
  { key: "usePathObfuscation", templateValue: false, reconstruction: "required" },
506
539
  { key: "idDerivationVersion", templateValue: 0, reconstruction: "required", knownDefault: 0 },
540
+ { key: "pathNormalizationVersion", templateValue: 0, reconstruction: "required", knownDefault: 0 },
507
541
  { key: "encryptInternalMetadata", templateValue: false, reconstruction: "none", knownDefault: false },
508
542
  { key: "enableCompression", templateValue: false, reconstruction: "none" },
509
543
  { key: "useEden", templateValue: false, reconstruction: "none" },
@@ -794,14 +828,35 @@ async function computeKeyedId(key, purpose, value) {
794
828
  return uint8ArrayToHexString(new Uint8Array(digest));
795
829
  }
796
830
 
831
+ // lib/livesync-commonlib/src/common/pathNormalization.ts
832
+ function assertSupportedPathNormalizationVersion(version) {
833
+ if (version === void 0 || version === 0 || version === 1) return;
834
+ throw new Error(`Unsupported path normalisation version: ${version}`);
835
+ }
836
+ function getPathNormalizationVersion(settings) {
837
+ const version = settings.pathNormalizationVersion === void 0 ? 0 : settings.pathNormalizationVersion;
838
+ assertSupportedPathNormalizationVersion(version);
839
+ return version;
840
+ }
841
+ function normalisePathForIdentity(path, version) {
842
+ const resolvedVersion = getPathNormalizationVersion({ pathNormalizationVersion: version });
843
+ return resolvedVersion === 1 ? path.normalize("NFC") : path;
844
+ }
845
+
797
846
  // lib/livesync-commonlib/src/pouchdb/remoteFeatureCompatibility.ts
798
847
  var REMOTE_FEATURE_GENERATION = 13;
799
848
  var ENCRYPTED_INTERNAL_METADATA_FEATURE = "encrypted-internal-metadata-v1";
800
849
  var INDEPENDENT_ID_DERIVATION_FEATURE = "independent-id-derivation-v1";
801
- var supportedFeatures = /* @__PURE__ */ new Set([ENCRYPTED_INTERNAL_METADATA_FEATURE, INDEPENDENT_ID_DERIVATION_FEATURE]);
850
+ var NFC_PATH_IDENTITY_FEATURE = "nfc-path-identity-v1";
851
+ var supportedFeatures = /* @__PURE__ */ new Set([
852
+ ENCRYPTED_INTERNAL_METADATA_FEATURE,
853
+ INDEPENDENT_ID_DERIVATION_FEATURE,
854
+ NFC_PATH_IDENTITY_FEATURE
855
+ ]);
802
856
  function requiredRemoteFeatures(setting) {
803
857
  const features = [];
804
858
  if (usesEncryptedInternalMetadata(setting)) features.push(ENCRYPTED_INTERNAL_METADATA_FEATURE);
859
+ if (getPathNormalizationVersion(setting) === 1) features.push(NFC_PATH_IDENTITY_FEATURE);
805
860
  if (setting.encrypt && configuredIdKey(setting)) features.push(INDEPENDENT_ID_DERIVATION_FEATURE);
806
861
  return features;
807
862
  }
@@ -971,6 +1026,75 @@ async function assessRemoteDocumentIds(db, setting, path2id) {
971
1026
  return matched ? "matching" : "unverified";
972
1027
  }
973
1028
 
1029
+ // lib/livesync-commonlib/src/pouchdb/pathIdentityCompatibility.ts
1030
+ async function inspectDatabasePathIdentity(database) {
1031
+ let document;
1032
+ try {
1033
+ document = await database.get(VERSIONING_DOCID);
1034
+ } catch (error) {
1035
+ if (!isErrorOfMissingDoc(error)) throw error;
1036
+ return (await database.info()).doc_count === 0 ? { status: "empty" } : { status: "configured", pathNormalizationVersion: 0 };
1037
+ }
1038
+ const assessment = assessRemoteFeatureDocument(document);
1039
+ if (assessment.status === "older-generation") return { status: "configured", pathNormalizationVersion: 0 };
1040
+ if (assessment.status !== "supported") throw new Error(describeRemoteFeatureRejection(assessment));
1041
+ return {
1042
+ status: "configured",
1043
+ pathNormalizationVersion: assessment.usedFeatures.includes(NFC_PATH_IDENTITY_FEATURE) ? 1 : 0
1044
+ };
1045
+ }
1046
+ function assertMatchingPathIdentityFeature(document, settings) {
1047
+ const assessment = assessRemoteFeatureDocument(document);
1048
+ const declared = assessment.status === "supported" && assessment.usedFeatures.includes(NFC_PATH_IDENTITY_FEATURE);
1049
+ if (declared !== (getPathNormalizationVersion(settings) === 1)) {
1050
+ throw new Error(
1051
+ "The database and settings use different path identity versions. Rebuild from the authoritative Vault or Fetch with matching settings before synchronising."
1052
+ );
1053
+ }
1054
+ }
1055
+ async function hasMetadata(database) {
1056
+ let startkey;
1057
+ for (; ; ) {
1058
+ const result = await database.allDocs({
1059
+ include_docs: true,
1060
+ limit: 100,
1061
+ ...startkey ? { startkey, skip: 1 } : {}
1062
+ });
1063
+ for (const row of result.rows) {
1064
+ if (row.doc?.type === "plain" || row.doc?.type === "newnote") return true;
1065
+ }
1066
+ if (result.rows.length < 100) return false;
1067
+ startkey = result.rows[result.rows.length - 1].id;
1068
+ }
1069
+ }
1070
+ async function assertDatabasePathIdentity(database, settings, declare = false) {
1071
+ let document;
1072
+ try {
1073
+ document = await database.get(VERSIONING_DOCID);
1074
+ } catch (error) {
1075
+ if (!isErrorOfMissingDoc(error)) throw error;
1076
+ }
1077
+ const assessment = assessRemoteFeatureDocument(document);
1078
+ const declared = assessment.status === "supported" && assessment.usedFeatures.includes(NFC_PATH_IDENTITY_FEATURE);
1079
+ if (getPathNormalizationVersion(settings) === 0) {
1080
+ if (declared) assertMatchingPathIdentityFeature(document, settings);
1081
+ return;
1082
+ }
1083
+ if (declared) return;
1084
+ if (await hasMetadata(database)) {
1085
+ try {
1086
+ document = await database.get(VERSIONING_DOCID);
1087
+ } catch (error) {
1088
+ if (!isErrorOfMissingDoc(error)) throw error;
1089
+ }
1090
+ assertMatchingPathIdentityFeature(document, settings);
1091
+ return;
1092
+ }
1093
+ if (declare && !await bumpRemoteVersion(database, REMOTE_FEATURE_GENERATION, [NFC_PATH_IDENTITY_FEATURE])) {
1094
+ throw new Error("The database path identity could not be declared. Synchronisation has been stopped.");
1095
+ }
1096
+ }
1097
+
974
1098
  // lib/livesync-commonlib/src/pouchdb/pouchdb-http.ts
975
1099
  import PouchDB from "pouchdb-core";
976
1100
  import HttpPouch from "pouchdb-adapter-http";
@@ -978,11 +1102,12 @@ import mapreduce from "pouchdb-mapreduce";
978
1102
  import replication from "pouchdb-replication";
979
1103
  import find from "pouchdb-find";
980
1104
  import transform from "transform-pouch";
1105
+
1106
+ // lib/livesync-commonlib/src/pouchdb/purgeMulti.ts
981
1107
  import { findPathToLeaf } from "pouchdb-merge";
982
1108
  import { adapterFun } from "pouchdb-utils";
983
1109
  import { createError, MISSING_DOC, UNKNOWN_ERROR } from "pouchdb-errors";
984
1110
  import { mapAllTasksWithConcurrencyLimit, unwrapTaskResult } from "octagonal-wheels/concurrency/task";
985
- PouchDB.plugin(HttpPouch).plugin(mapreduce).plugin(replication).plugin(find).plugin(transform);
986
1111
  function appendPurgeSeqs(db, docs) {
987
1112
  return db.get("_local/purges").then(function(doc) {
988
1113
  for (const [docId, rev$$1] of docs) {
@@ -1015,54 +1140,110 @@ function appendPurgeSeqs(db, docs) {
1015
1140
  return db.put(doc);
1016
1141
  });
1017
1142
  }
1018
- PouchDB.prototype.purgeMulti = adapterFun(
1019
- "_purgeMulti",
1020
- function(docs, callback) {
1021
- if (typeof this._purge === "undefined") {
1022
- return callback(
1023
- //@ts-ignore: this ts-ignore might be hiding a `this` bug where we don't have "this" conext.
1024
- createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter.")
1025
- );
1026
- }
1027
- const self = this;
1028
- const tasks = docs.map(
1029
- (param) => () => new Promise((res, rej) => {
1030
- const [docId, rev$$1] = param;
1031
- self._getRevisionTree(docId, (error, revs) => {
1032
- if (error) {
1033
- return res([param, error]);
1034
- }
1035
- if (!revs) {
1036
- return res([param, createError(MISSING_DOC)]);
1037
- }
1038
- let path;
1039
- try {
1040
- path = findPathToLeaf(revs, rev$$1);
1041
- } catch (error2) {
1042
- return res([param, error2.message || error2]);
1043
- }
1044
- self._purge(docId, path, (error2, result) => {
1045
- if (error2) {
1046
- return res([param, error2]);
1047
- } else {
1048
- return res([param, result]);
1143
+ function installPurgeMulti(PouchDB2) {
1144
+ PouchDB2.prototype.purgeMulti = adapterFun(
1145
+ "_purgeMulti",
1146
+ function(docs, callback) {
1147
+ if (typeof this._purge === "undefined") {
1148
+ return callback(
1149
+ //@ts-ignore: this ts-ignore might be hiding a `this` bug where we don't have "this" conext.
1150
+ createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter.")
1151
+ );
1152
+ }
1153
+ const self = this;
1154
+ const tasks = docs.map(
1155
+ (param) => () => new Promise((res, rej) => {
1156
+ const [docId, rev$$1] = param;
1157
+ self._getRevisionTree(docId, (error, revs) => {
1158
+ if (error) {
1159
+ return res([param, error]);
1160
+ }
1161
+ if (!revs) {
1162
+ return res([param, createError(MISSING_DOC)]);
1049
1163
  }
1164
+ let path;
1165
+ try {
1166
+ path = findPathToLeaf(revs, rev$$1);
1167
+ } catch (error2) {
1168
+ return res([param, error2.message || error2]);
1169
+ }
1170
+ self._purge(docId, path, (error2, result) => {
1171
+ if (error2) {
1172
+ return res([param, error2]);
1173
+ } else {
1174
+ return res([param, result]);
1175
+ }
1176
+ });
1050
1177
  });
1051
- });
1052
- })
1053
- );
1054
- (async () => {
1055
- const ret = await mapAllTasksWithConcurrencyLimit(1, tasks);
1056
- const retAll = ret.map((e) => unwrapTaskResult(e));
1057
- await appendPurgeSeqs(
1058
- self,
1059
- retAll.filter((e) => "ok" in e[1]).map((e) => e[0])
1178
+ })
1060
1179
  );
1061
- const result = Object.fromEntries(retAll.map((e) => [e[0][0], e[1]]));
1062
- return result;
1063
- })().then((result) => callback(void 0, result)).catch((error) => callback(error));
1180
+ (async () => {
1181
+ const ret = await mapAllTasksWithConcurrencyLimit(1, tasks);
1182
+ const retAll = ret.map((e) => unwrapTaskResult(e));
1183
+ await appendPurgeSeqs(
1184
+ self,
1185
+ retAll.filter((e) => "ok" in e[1]).map((e) => e[0])
1186
+ );
1187
+ const result = Object.fromEntries(retAll.map((e) => [e[0][0], e[1]]));
1188
+ return result;
1189
+ })().then((result) => callback(void 0, result)).catch((error) => callback(error));
1190
+ }
1191
+ );
1192
+ }
1193
+
1194
+ // lib/livesync-commonlib/src/pouchdb/pouchdb-http.ts
1195
+ PouchDB.plugin(HttpPouch).plugin(mapreduce).plugin(replication).plugin(find).plugin(transform);
1196
+ installPurgeMulti(PouchDB);
1197
+
1198
+ // lib/livesync-commonlib/src/replication/unencryptedContentMessages.ts
1199
+ var rejectionConsequences = {
1200
+ replication: "Synchronisation stopped",
1201
+ "on-demand": "File content could not be retrieved",
1202
+ "fast-fetch": "Fast Fetch stopped without completing"
1203
+ };
1204
+ function getUnencryptedContentRejectionMessage(operation) {
1205
+ const nextAction = operation === "on-demand" ? ", then retry the file retrieval." : ".";
1206
+ return `${rejectionConsequences[operation]} because unencrypted content was rejected. Review the remote data and 'Accept unencrypted content' in the E2EE Advanced settings${nextAction}`;
1207
+ }
1208
+
1209
+ // lib/livesync-commonlib/src/replication/UnencryptedContentRejectedError.ts
1210
+ var UNENCRYPTED_CONTENT_REJECTED_CODE = "UNENCRYPTED_CONTENT_REJECTED";
1211
+ var UNENCRYPTED_CONTENT_REJECTED_NAME = "UnencryptedContentRejectedError";
1212
+ var UnencryptedContentRejectedError = class extends Error {
1213
+ constructor(documentId, contentKind) {
1214
+ super(`Unencrypted ${contentKind} content in remote document ${documentId} was rejected while E2EE is enabled.`);
1215
+ this.documentId = documentId;
1216
+ this.contentKind = contentKind;
1064
1217
  }
1065
- );
1218
+ name = UNENCRYPTED_CONTENT_REJECTED_NAME;
1219
+ code = UNENCRYPTED_CONTENT_REJECTED_CODE;
1220
+ };
1221
+ function inspectUnencryptedContentRejection(error) {
1222
+ const seen = /* @__PURE__ */ new Set();
1223
+ const pending = [error];
1224
+ let details;
1225
+ let rejected = false;
1226
+ while (pending.length > 0) {
1227
+ const current = pending.pop();
1228
+ if (typeof current !== "object" || current === null || seen.has(current)) continue;
1229
+ seen.add(current);
1230
+ const candidate = current;
1231
+ if (candidate.code === UNENCRYPTED_CONTENT_REJECTED_CODE || candidate.name === UNENCRYPTED_CONTENT_REJECTED_NAME) {
1232
+ rejected = true;
1233
+ if (typeof candidate.documentId === "string" && typeof candidate.contentKind === "string") {
1234
+ details ??= { documentId: candidate.documentId, contentKind: candidate.contentKind };
1235
+ }
1236
+ }
1237
+ if ("cause" in candidate) pending.push(candidate.cause);
1238
+ }
1239
+ return { rejected, details };
1240
+ }
1241
+ function isUnencryptedContentRejectedError(error) {
1242
+ return inspectUnencryptedContentRejection(error).rejected;
1243
+ }
1244
+ function getUnencryptedContentRejection(error) {
1245
+ return inspectUnencryptedContentRejection(error).details;
1246
+ }
1066
1247
 
1067
1248
  // lib/livesync-commonlib/src/managers/ChunkFetcher.ts
1068
1249
  import { delay, promiseWithResolvers as promiseWithResolvers2 } from "octagonal-wheels/promises";
@@ -1230,7 +1411,7 @@ function decideMissingChunkAction({
1230
1411
  }
1231
1412
  function isValidChunk(chunk) {
1232
1413
  const candidate = chunk;
1233
- return !!candidate && typeof candidate._id === "string" && typeof candidate.data === "string";
1414
+ return !!candidate && candidate.type === "leaf" && typeof candidate._id === "string" && !candidate._id.startsWith("_local/") && typeof candidate.data === "string";
1234
1415
  }
1235
1416
  function classifyFetchedChunks(requestedIds, fetched) {
1236
1417
  const chunks = [];
@@ -1493,7 +1674,11 @@ var ChunkFetcher = class {
1493
1674
  logger_exports.LOG_LEVEL_VERBOSE
1494
1675
  );
1495
1676
  for (const chunk of invalidChunks) {
1496
- (0, logger_exports.Logger)(`Invalid chunk: ${JSON.stringify(chunk)}`, logger_exports.LOG_LEVEL_VERBOSE);
1677
+ const id = typeof chunk === "object" && chunk !== null && "_id" in chunk && typeof chunk._id === "string" ? chunk._id : void 0;
1678
+ (0, logger_exports.Logger)(
1679
+ id === void 0 ? "Invalid chunk without a string document ID." : `Invalid chunk document: ${JSON.stringify(id)}`,
1680
+ logger_exports.LOG_LEVEL_VERBOSE
1681
+ );
1497
1682
  }
1498
1683
  }
1499
1684
  if (chunks.length === 0) {
@@ -1569,20 +1754,25 @@ var ChunkFetcher = class {
1569
1754
  await this.resolveLocallyAvailableRetries(requestClaims);
1570
1755
  let pendingIDs = await this.waitBeforeRemoteRequest(requestIDs, requestClaims, localCheckCompletionVersion);
1571
1756
  if (pendingIDs.length === 0) return;
1572
- const replicator = this.options.replicatorService.getActiveReplicator();
1573
- if (!replicator) {
1574
- (0, logger_exports.Logger)("No active replicator was found to request missing chunks.");
1575
- return;
1576
- }
1577
- if (!canFetchRemoteChunks(replicator)) {
1578
- (0, logger_exports.Logger)("The active replicator does not support fetching individual remote chunks.");
1579
- for (const chunkID of pendingIDs) {
1580
- this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
1757
+ const requestCompletionVersion = this.finiteCompletionVersion;
1758
+ let fetched;
1759
+ if (this.options.source) {
1760
+ fetched = await this.options.source.fetchChunks(pendingIDs);
1761
+ } else {
1762
+ const replicator = this.options.replicatorService.getActiveReplicator();
1763
+ if (!replicator) {
1764
+ (0, logger_exports.Logger)("No active replicator was found to request missing chunks.");
1765
+ return;
1581
1766
  }
1582
- return;
1767
+ if (!canFetchRemoteChunks(replicator)) {
1768
+ (0, logger_exports.Logger)("The active replicator does not support fetching individual remote chunks.");
1769
+ for (const chunkID of pendingIDs) {
1770
+ this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
1771
+ }
1772
+ return;
1773
+ }
1774
+ fetched = await replicator.fetchRemoteChunks(pendingIDs, false);
1583
1775
  }
1584
- const requestCompletionVersion = this.finiteCompletionVersion;
1585
- const fetched = await replicator.fetchRemoteChunks(pendingIDs, false);
1586
1776
  pendingIDs = this.getActiveClaimIds(pendingIDs, requestClaims);
1587
1777
  this.touchClaims(pendingIDs, requestClaims);
1588
1778
  if (!fetched) {
@@ -1596,7 +1786,9 @@ var ChunkFetcher = class {
1596
1786
  this.logFetchedChunks(pendingIDs, classification);
1597
1787
  const { chunks, missingIds, invalidIds } = classification;
1598
1788
  try {
1599
- if (chunks.length > 0) {
1789
+ if (chunks.length > 0 && this.options.source) {
1790
+ await this.options.source.storeChunks(chunks);
1791
+ } else if (chunks.length > 0) {
1600
1792
  (0, logger_exports.Logger)(`Writing fetched chunks (${chunks.length}) to the database...`);
1601
1793
  const result = await this.chunkManager.write(
1602
1794
  chunks,
@@ -1632,8 +1824,22 @@ var ChunkFetcher = class {
1632
1824
  }
1633
1825
  this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);
1634
1826
  } catch (error) {
1635
- (0, logger_exports.Logger)("An error occurred while fetching remote chunks.", logger_exports.LOG_LEVEL_VERBOSE);
1636
- (0, logger_exports.Logger)(error, logger_exports.LOG_LEVEL_VERBOSE);
1827
+ if (isUnencryptedContentRejectedError(error)) {
1828
+ (0, logger_exports.Logger)(
1829
+ getUnencryptedContentRejectionMessage("on-demand"),
1830
+ logger_exports.LOG_LEVEL_NOTICE,
1831
+ "unencrypted-content-rejected"
1832
+ );
1833
+ const rejection = getUnencryptedContentRejection(error);
1834
+ const identifiers = rejection ? [rejection.documentId] : requestIDs;
1835
+ (0, logger_exports.Logger)(
1836
+ `On-demand retrieval rejected unencrypted content: ${identifiers.join(", ")}`,
1837
+ logger_exports.LOG_LEVEL_VERBOSE
1838
+ );
1839
+ } else {
1840
+ (0, logger_exports.Logger)("An error occurred while fetching remote chunks.", logger_exports.LOG_LEVEL_VERBOSE);
1841
+ (0, logger_exports.Logger)(error, logger_exports.LOG_LEVEL_VERBOSE);
1842
+ }
1637
1843
  } finally {
1638
1844
  for (const [id, pending] of requestClaims) {
1639
1845
  if (pending.inFlight) this.settleClaim(id, pending);
@@ -1651,6 +1857,14 @@ import { FallbackWeakRef as FallbackWeakRef3 } from "octagonal-wheels/common/pol
1651
1857
  // lib/livesync-commonlib/src/common/utils.ts
1652
1858
  import { LRUCache } from "octagonal-wheels/memory/LRUCache";
1653
1859
 
1860
+ // lib/livesync-commonlib/src/common/pathNamespace.ts
1861
+ function splitPathNamespace(path) {
1862
+ for (const prefix of [ICHeader, ICXHeader, PSCHeader]) {
1863
+ if (path.startsWith(prefix)) return [prefix, path.slice(prefix.length)];
1864
+ }
1865
+ return ["", path];
1866
+ }
1867
+
1654
1868
  // lib/livesync-commonlib/src/string_and_binary/path.ts
1655
1869
  import { Minimatch } from "minimatch";
1656
1870
  import { unique as unique2 } from "octagonal-wheels/collection.js";
@@ -1669,12 +1883,8 @@ function addPrefix(path, prefix) {
1669
1883
  return `${prefix ?? ""}${path}`;
1670
1884
  }
1671
1885
  function expandFilePathPrefix(path) {
1672
- for (const prefix of [ICHeader, ICXHeader, PSCHeader]) {
1673
- if (path.startsWith(prefix)) {
1674
- return [prefix, path.substring(prefix.length)];
1675
- }
1676
- }
1677
- return ["", path];
1886
+ const [prefix, body] = splitPathNamespace(path);
1887
+ return [prefix, body];
1678
1888
  }
1679
1889
  function expandDocumentIDPrefix(id) {
1680
1890
  for (const prefix of [CHeader, PREFIX_OBFUSCATED]) {
@@ -1728,6 +1938,18 @@ function getPath(entry) {
1728
1938
  function stripPrefix(prefixedPath) {
1729
1939
  return expandFilePathPrefix(prefixedPath)[1];
1730
1940
  }
1941
+ function isPlainText(filename) {
1942
+ if (filename.endsWith(".md")) return true;
1943
+ if (filename.endsWith(".txt")) return true;
1944
+ if (filename.endsWith(".svg")) return true;
1945
+ if (filename.endsWith(".html")) return true;
1946
+ if (filename.endsWith(".csv")) return true;
1947
+ if (filename.endsWith(".css")) return true;
1948
+ if (filename.endsWith(".js")) return true;
1949
+ if (filename.endsWith(".xml")) return true;
1950
+ if (filename.endsWith(".canvas")) return true;
1951
+ return false;
1952
+ }
1731
1953
  function shouldSplitAsPlainText(filename) {
1732
1954
  if (filename.endsWith(".md")) return true;
1733
1955
  if (filename.endsWith(".txt")) return true;
@@ -1737,8 +1959,10 @@ function shouldSplitAsPlainText(filename) {
1737
1959
 
1738
1960
  // lib/livesync-commonlib/src/common/utils.ts
1739
1961
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
1740
- import { replaceAll, replaceAllPairs } from "octagonal-wheels/string";
1962
+ import { joinDelimitedList, replaceAll, replaceAllPairs, splitDelimitedList } from "octagonal-wheels/string";
1963
+ import { formatDuration } from "octagonal-wheels/notation/duration";
1741
1964
  import { concatUInt8Array } from "octagonal-wheels/binary";
1965
+ import { createBinaryBlob, createTextBlob, isBlobContentEqual, toBlob } from "octagonal-wheels/binary/blob";
1742
1966
  import { delay as delay2, fireAndForget } from "octagonal-wheels/promises";
1743
1967
  import { arrayToChunkedArray, unique as unique3 } from "octagonal-wheels/collection";
1744
1968
  import { extractObject, isObjectDifferent } from "octagonal-wheels/object";
@@ -1855,8 +2079,9 @@ var LiveSyncError = class _LiveSyncError extends Error {
1855
2079
  };
1856
2080
 
1857
2081
  // lib/livesync-commonlib/src/common/utils.object.ts
2082
+ import { cloneViaJSON } from "octagonal-wheels/encoding/json";
1858
2083
  function asCopy(obj) {
1859
- return JSON.parse(JSON.stringify(obj));
2084
+ return cloneViaJSON(obj);
1860
2085
  }
1861
2086
 
1862
2087
  // lib/livesync-commonlib/src/common/utils.patch.ts
@@ -1864,6 +2089,17 @@ var MARK_OPERATOR = ``;
1864
2089
  var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;
1865
2090
  var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;
1866
2091
  var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;
2092
+ function hasOwnProperty(target, key) {
2093
+ return Object.prototype.hasOwnProperty.call(target, key);
2094
+ }
2095
+ function setOwnProperty(target, key, value) {
2096
+ Object.defineProperty(target, key, {
2097
+ value,
2098
+ enumerable: true,
2099
+ configurable: true,
2100
+ writable: true
2101
+ });
2102
+ }
1867
2103
  function unorderedArrayToObject(obj) {
1868
2104
  return obj.map((e) => ({ [e.id]: e })).reduce((p, c) => ({ ...p, ...c }), {});
1869
2105
  }
@@ -1892,34 +2128,34 @@ function generatePatchObj(from, to) {
1892
2128
  const newEntries = Object.entries(to);
1893
2129
  for (const [key, value] of newEntries) {
1894
2130
  if (!tempMap.has(key)) {
1895
- ret[key] = value;
2131
+ setOwnProperty(ret, key, value);
1896
2132
  tempMap.delete(key);
1897
2133
  } else {
1898
2134
  const v = tempMap.get(key);
1899
2135
  if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) {
1900
- ret[key] = { [MARK_SWAPPED]: value };
2136
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1901
2137
  } else {
1902
2138
  if (v === null && value === null) {
1903
2139
  } else if (v === null && value !== null) {
1904
- ret[key] = { [MARK_SWAPPED]: value };
2140
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1905
2141
  } else if (v !== null && value === null) {
1906
- ret[key] = { [MARK_SWAPPED]: value };
2142
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1907
2143
  } else if (typeof v == "object" && typeof value == "object" && !Array.isArray(v) && !Array.isArray(value)) {
1908
2144
  const wk = generatePatchObj(
1909
2145
  v,
1910
2146
  value
1911
2147
  );
1912
- if (Object.keys(wk).length > 0) ret[key] = wk;
2148
+ if (Object.keys(wk).length > 0) setOwnProperty(ret, key, wk);
1913
2149
  } else if (typeof v == "object" && typeof value == "object" && Array.isArray(v) && Array.isArray(value)) {
1914
2150
  const wk = generatePatchUnorderedArray(v, value);
1915
- if (Object.keys(wk).length > 0) ret[key] = wk;
2151
+ if (Object.keys(wk).length > 0) setOwnProperty(ret, key, wk);
1916
2152
  } else if (typeof v != "object" && typeof value != "object") {
1917
2153
  if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
1918
- ret[key] = value;
2154
+ setOwnProperty(ret, key, value);
1919
2155
  }
1920
2156
  } else {
1921
2157
  if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
1922
- ret[key] = { [MARK_SWAPPED]: value };
2158
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1923
2159
  }
1924
2160
  }
1925
2161
  }
@@ -1927,7 +2163,7 @@ function generatePatchObj(from, to) {
1927
2163
  }
1928
2164
  }
1929
2165
  for (const [key] of tempMap) {
1930
- ret[key] = MARK_DELETED;
2166
+ setOwnProperty(ret, key, MARK_DELETED);
1931
2167
  }
1932
2168
  return ret;
1933
2169
  }
@@ -1935,21 +2171,21 @@ function applyPatch(from, patch) {
1935
2171
  const ret = from;
1936
2172
  const patches = Object.entries(patch);
1937
2173
  for (const [key, value] of patches) {
1938
- if (value == MARK_DELETED) {
2174
+ if (value === MARK_DELETED) {
1939
2175
  delete ret[key];
1940
2176
  continue;
1941
2177
  }
1942
2178
  if (value === null) {
1943
- ret[key] = null;
2179
+ setOwnProperty(ret, key, null);
1944
2180
  continue;
1945
2181
  }
1946
2182
  if (typeof value == "object") {
1947
- if (MARK_SWAPPED in value) {
1948
- ret[key] = value[MARK_SWAPPED];
2183
+ if (hasOwnProperty(value, MARK_SWAPPED)) {
2184
+ setOwnProperty(ret, key, value[MARK_SWAPPED]);
1949
2185
  continue;
1950
2186
  }
1951
- if (MARK_ISARRAY in value) {
1952
- if (!(key in ret)) ret[key] = [];
2187
+ if (hasOwnProperty(value, MARK_ISARRAY)) {
2188
+ if (!hasOwnProperty(ret, key)) setOwnProperty(ret, key, []);
1953
2189
  if (!Array.isArray(ret[key])) {
1954
2190
  throw new Error("Patch target type is mismatched (array to something)");
1955
2191
  }
@@ -1959,19 +2195,23 @@ function applyPatch(from, patch) {
1959
2195
  value[MARK_ISARRAY]
1960
2196
  );
1961
2197
  const appliedArray = objectToUnorderedArray(appliedObject);
1962
- ret[key] = [...appliedArray];
2198
+ setOwnProperty(ret, key, [...appliedArray]);
1963
2199
  } else {
1964
- if (!(key in ret)) {
1965
- ret[key] = value;
2200
+ if (!hasOwnProperty(ret, key)) {
2201
+ setOwnProperty(ret, key, value);
1966
2202
  continue;
1967
2203
  }
1968
- ret[key] = applyPatch(
1969
- ret[key],
1970
- value
2204
+ setOwnProperty(
2205
+ ret,
2206
+ key,
2207
+ applyPatch(
2208
+ ret[key],
2209
+ value
2210
+ )
1971
2211
  );
1972
2212
  }
1973
2213
  } else {
1974
- ret[key] = value;
2214
+ setOwnProperty(ret, key, value);
1975
2215
  }
1976
2216
  }
1977
2217
  return ret;
@@ -2005,27 +2245,31 @@ function getDocData(doc) {
2005
2245
  function isTextBlob(blob) {
2006
2246
  return blob.type === "text/plain";
2007
2247
  }
2008
- function createTextBlob(data) {
2009
- const d = Array.isArray(data) ? data : [data];
2010
- return new Blob(d, { endings: "transparent", type: "text/plain" });
2248
+ function createBlob(data) {
2249
+ return toBlob(data);
2011
2250
  }
2012
- function createBinaryBlob(data) {
2013
- return new Blob([data], { endings: "transparent", type: "application/octet-stream" });
2251
+ function isTextDocument(doc) {
2252
+ if (doc.type == "plain") return true;
2253
+ if (doc.datatype == "plain") return true;
2254
+ if (isPlainText(doc.path)) return true;
2255
+ return false;
2014
2256
  }
2015
- function createBlob(data) {
2016
- if (data instanceof Blob) return data;
2017
- if (data instanceof Uint8Array || data instanceof ArrayBuffer) return createBinaryBlob(data);
2018
- return createTextBlob(data);
2257
+ function readContent(doc) {
2258
+ if (isTextDocument(doc)) {
2259
+ return getDocData(doc.data);
2260
+ } else {
2261
+ return decodeBinary(doc.data);
2262
+ }
2019
2263
  }
2020
2264
  var isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== "undefined";
2021
2265
  function isObfuscatedEntry(doc) {
2022
- if (doc._id.startsWith(PREFIX_OBFUSCATED)) {
2266
+ if (doc._id.startsWith(IDPrefixes.Obfuscated)) {
2023
2267
  return true;
2024
2268
  }
2025
2269
  return false;
2026
2270
  }
2027
2271
  function isEncryptedChunkEntry(doc) {
2028
- if (doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) {
2272
+ if (doc._id.startsWith(IDPrefixes.EncryptedChunk)) {
2029
2273
  return true;
2030
2274
  }
2031
2275
  return false;
@@ -2583,14 +2827,16 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
2583
2827
  }
2584
2828
  }
2585
2829
  const chunkUnitBinary = 256 * 1024;
2586
- const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4;
2587
2830
  const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16;
2588
- const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary;
2589
2831
  const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;
2590
2832
  const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);
2591
2833
  const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);
2592
- const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);
2593
- const avgChunkSize = Math.min(Math.max(fixedAvgChunkSize, minChunkSize), maxChunkSize);
2834
+ const proportionalGap = Math.max(1, Math.floor(maxChunkSize / 4));
2835
+ const minChunkSize = Math.min(
2836
+ Math.max(plainSplit ? chunkUnitPlain * 2 : proportionalGap, minimumChunkSize),
2837
+ maxChunkSize
2838
+ );
2839
+ const avgChunkSize = plainSplit ? Math.min(Math.max(chunkUnitPlain * 4, minChunkSize), maxChunkSize) : proportionalGap;
2594
2840
  const windowSize = 48;
2595
2841
  const hashModulus = avgChunkSize;
2596
2842
  const boundaryPattern = 1;
@@ -2608,7 +2854,7 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
2608
2854
  return async function* piecesBlob() {
2609
2855
  while (pos < length) {
2610
2856
  const byte = buffer[pos];
2611
- if (pos >= start + windowSize) {
2857
+ if (pos >= windowSize) {
2612
2858
  const oldByte = buffer[pos - windowSize];
2613
2859
  const oldByteTerm = Math.imul(oldByte, P_pow_w);
2614
2860
  hash = hash - oldByteTerm | 0;
@@ -2699,23 +2945,8 @@ var ContentSplitterRabinKarp = class extends ContentSplitterBase {
2699
2945
  return settings.chunkSplitterVersion === ChunkAlgorithms.RabinKarp;
2700
2946
  }
2701
2947
  async processSplit(options) {
2702
- if (options.useWorker) {
2703
- return (await splitPieces2WorkerRabinKarp(
2704
- options.blob,
2705
- options.pieceSize,
2706
- options.plainSplit,
2707
- options.minimumChunkSize,
2708
- options.path
2709
- ))();
2710
- } else {
2711
- return (await splitPiecesRabinKarp(
2712
- options.blob,
2713
- options.pieceSize,
2714
- options.plainSplit,
2715
- options.minimumChunkSize,
2716
- options.path
2717
- ))();
2718
- }
2948
+ const split = options.useWorker ? splitPieces2WorkerRabinKarp : splitPiecesRabinKarp;
2949
+ return (await split(options.blob, options.pieceSize, options.plainSplit, options.minimumChunkSize, options.path))();
2719
2950
  }
2720
2951
  };
2721
2952
 
@@ -2726,25 +2957,15 @@ var ContentSplitterV1 = class extends ContentSplitterBase {
2726
2957
  return settings.chunkSplitterVersion === ChunkAlgorithms.V1 || settings.chunkSplitterVersion === "" || settings.chunkSplitterVersion === void 0;
2727
2958
  }
2728
2959
  async processSplit(options) {
2729
- if (options.useWorker) {
2730
- return (await splitPieces2Worker(
2731
- options.blob,
2732
- options.pieceSize,
2733
- options.plainSplit,
2734
- options.minimumChunkSize,
2735
- options.path,
2736
- options.useSegmenter
2737
- ))();
2738
- } else {
2739
- return (await splitPieces2(
2740
- options.blob,
2741
- options.pieceSize,
2742
- options.plainSplit,
2743
- options.minimumChunkSize,
2744
- options.path,
2745
- options.useSegmenter
2746
- ))();
2747
- }
2960
+ const split = options.useWorker ? splitPieces2Worker : splitPieces2;
2961
+ return (await split(
2962
+ options.blob,
2963
+ options.pieceSize,
2964
+ options.plainSplit,
2965
+ options.minimumChunkSize,
2966
+ options.path,
2967
+ options.useSegmenter
2968
+ ))();
2748
2969
  }
2749
2970
  };
2750
2971
 
@@ -2755,25 +2976,15 @@ var ContentSplitterV2 = class extends ContentSplitterBase {
2755
2976
  return settings.chunkSplitterVersion === ChunkAlgorithms.V2 || settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter;
2756
2977
  }
2757
2978
  async processSplit(options) {
2758
- if (options.useWorker) {
2759
- return (await splitPieces2WorkerV2(
2760
- options.blob,
2761
- options.pieceSize,
2762
- options.plainSplit,
2763
- options.minimumChunkSize,
2764
- options.path,
2765
- options.useSegmenter
2766
- ))();
2767
- } else {
2768
- return (await splitPieces2V2(
2769
- options.blob,
2770
- options.pieceSize,
2771
- options.plainSplit,
2772
- options.minimumChunkSize,
2773
- options.path,
2774
- options.useSegmenter
2775
- ))();
2776
- }
2979
+ const split = options.useWorker ? splitPieces2WorkerV2 : splitPieces2V2;
2980
+ return (await split(
2981
+ options.blob,
2982
+ options.pieceSize,
2983
+ options.plainSplit,
2984
+ options.minimumChunkSize,
2985
+ options.path,
2986
+ options.useSegmenter
2987
+ ))();
2777
2988
  }
2778
2989
  };
2779
2990
 
@@ -3864,7 +4075,7 @@ var ConflictManager = class {
3864
4075
  };
3865
4076
 
3866
4077
  // lib/livesync-commonlib/src/managers/EntryManager/EntryManagerImpls.ts
3867
- import { Logger as Logger9, LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE9, LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE3 } from "octagonal-wheels/common/logger";
4078
+ import { Logger as Logger9, LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE9, LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE4 } from "octagonal-wheels/common/logger";
3868
4079
  import { serialized } from "octagonal-wheels/concurrency/lock";
3869
4080
  async function createChunks(managers, dispFilename, note) {
3870
4081
  const { chunkManager, splitter } = managers;
@@ -3897,7 +4108,7 @@ async function createChunks(managers, dispFilename, note) {
3897
4108
  note._id
3898
4109
  );
3899
4110
  if (result.result === false) {
3900
- Logger9(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
4111
+ Logger9(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE4);
3901
4112
  return false;
3902
4113
  }
3903
4114
  totalWritingCount++;
@@ -3911,7 +4122,7 @@ async function createChunks(managers, dispFilename, note) {
3911
4122
  const flushIfNeeded = async () => {
3912
4123
  if (bufferedSize > MAX_WRITE_SIZE) {
3913
4124
  if (!await flushBufferedChunks()) {
3914
- Logger9(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
4125
+ Logger9(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE4);
3915
4126
  return false;
3916
4127
  }
3917
4128
  }
@@ -3961,7 +4172,7 @@ async function createChunks(managers, dispFilename, note) {
3961
4172
  if (dataSize > 0 && totalWritingCount === 0) {
3962
4173
  Logger9(
3963
4174
  `No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,
3964
- LOG_LEVEL_NOTICE3
4175
+ LOG_LEVEL_NOTICE4
3965
4176
  );
3966
4177
  }
3967
4178
  return chunks;
@@ -4018,7 +4229,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4018
4229
  path: note.path,
4019
4230
  ctime: note.ctime,
4020
4231
  mtime: note.mtime,
4021
- size: note.size,
4232
+ size: data.size,
4022
4233
  type: note.datatype,
4023
4234
  eden: {}
4024
4235
  };
@@ -4054,7 +4265,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4054
4265
  }) ?? false;
4055
4266
  });
4056
4267
  if (result === false) {
4057
- Logger9(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE3);
4268
+ Logger9(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE4);
4058
4269
  return false;
4059
4270
  }
4060
4271
  Logger9(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE9);
@@ -4062,7 +4273,8 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4062
4273
  }
4063
4274
  function isTargetFile(host, filenameSrc) {
4064
4275
  const settings = host.services.setting.currentSettings();
4065
- const file = filenameSrc.startsWith(ICHeader) ? filenameSrc.substring(ICHeader.length) : filenameSrc;
4276
+ const isInternalFile = filenameSrc.startsWith(ICHeader);
4277
+ const file = isInternalFile ? filenameSrc.substring(ICHeader.length) : filenameSrc;
4066
4278
  if (file.startsWith(ICXHeader)) return true;
4067
4279
  if (file.startsWith(PSCHeader)) return true;
4068
4280
  if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) {
@@ -4073,7 +4285,7 @@ function isTargetFile(host, filenameSrc) {
4073
4285
  return false;
4074
4286
  }
4075
4287
  }
4076
- if (settings.syncOnlyRegEx) {
4288
+ if (!isInternalFile && settings.syncOnlyRegEx) {
4077
4289
  const syncOnly = getFileRegExp(settings, "syncOnlyRegEx");
4078
4290
  if (syncOnly.length > 0 && !syncOnly.some((e) => e.test(file))) return false;
4079
4291
  }
@@ -4103,12 +4315,29 @@ async function getDBEntryMetaByPath(host, { localDatabase }, path, opt, includeD
4103
4315
  const id = await host.services.path.path2id(path);
4104
4316
  try {
4105
4317
  let obj = null;
4106
- if (opt) {
4107
- obj = await localDatabase.get(id, opt);
4108
- } else {
4109
- obj = await localDatabase.get(id);
4318
+ try {
4319
+ if (opt) {
4320
+ obj = await localDatabase.get(id, opt);
4321
+ } else {
4322
+ obj = await localDatabase.get(id);
4323
+ }
4324
+ } catch (ex) {
4325
+ if (!includeDeleted || opt?.rev !== void 0 || !isErrorOfMissingDoc(ex)) throw ex;
4326
+ for (let attempt = 0; attempt < 3; attempt++) {
4327
+ const result = await localDatabase.allDocs({ keys: [id] });
4328
+ const row = result.rows[0];
4329
+ if (!row || !("value" in row) || !row.value.rev) return false;
4330
+ const candidate = await localDatabase.get(id, { ...opt, rev: row.value.rev });
4331
+ const current = (await localDatabase.allDocs({ keys: [id] })).rows[0];
4332
+ if (!current || !("value" in current) || !current.value.rev) return false;
4333
+ if (current.value.rev === candidate._rev) {
4334
+ obj = candidate;
4335
+ break;
4336
+ }
4337
+ }
4338
+ if (!obj) return false;
4110
4339
  }
4111
- const deleted = obj?.deleted ?? obj._deleted ?? void 0;
4340
+ const deleted = obj._deleted || obj.deleted;
4112
4341
  if (!includeDeleted && deleted) return false;
4113
4342
  if (obj.type && obj.type == "leaf") {
4114
4343
  return false;
@@ -4290,13 +4519,13 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
4290
4519
  if (isErrorOfMissingDoc(ex)) {
4291
4520
  Logger9(
4292
4521
  `Missing document content!, could not read ${dispFilename}(${meta._id.substring(0, 8)}) from database.`,
4293
- LOG_LEVEL_NOTICE3
4522
+ LOG_LEVEL_NOTICE4
4294
4523
  );
4295
4524
  return false;
4296
4525
  }
4297
4526
  Logger9(
4298
4527
  `Something went wrong on reading ${dispFilename}(${meta._id.substring(0, 8)}) from database:`,
4299
- LOG_LEVEL_NOTICE3
4528
+ LOG_LEVEL_NOTICE4
4300
4529
  );
4301
4530
  Logger9(ex);
4302
4531
  }
@@ -4464,21 +4693,29 @@ var EntryManager = class {
4464
4693
  return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);
4465
4694
  }
4466
4695
  async deleteDBEntry(path, opt) {
4696
+ await this.checkPathIdentity();
4467
4697
  return await deleteDBEntryByPath(this.serviceHost, this, path, opt);
4468
4698
  }
4469
4699
  async storeDeletionAtRevision(path, baseRevision) {
4700
+ await this.checkPathIdentity();
4470
4701
  return await storeDeletionByPathAtRevision(this.serviceHost, this, path, baseRevision);
4471
4702
  }
4472
4703
  async putDBEntry(note, onlyChunks, conflictBaseRev) {
4704
+ await this.checkPathIdentity();
4473
4705
  return await putDBEntry(this.serviceHost, this, note, onlyChunks, conflictBaseRev);
4474
4706
  }
4475
4707
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
4708
+ await this.checkPathIdentity();
4476
4709
  return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);
4477
4710
  }
4478
4711
  /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */
4479
4712
  async putDBEntryAsIndependentRoot(note) {
4713
+ await this.checkPathIdentity();
4480
4714
  return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);
4481
4715
  }
4716
+ async checkPathIdentity() {
4717
+ await assertDatabasePathIdentity(this.localDatabase, this.options.settingService.currentSettings(), true);
4718
+ }
4482
4719
  };
4483
4720
 
4484
4721
  // lib/livesync-commonlib/src/managers/HashManager/HashManagerCore.ts
@@ -4886,7 +5123,7 @@ var HashManager = class extends HashManagerCore {
4886
5123
  // lib/livesync-commonlib/src/services/lib/logUtils.ts
4887
5124
  import {
4888
5125
  LOG_LEVEL_INFO as LOG_LEVEL_INFO4,
4889
- LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE4,
5126
+ LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE5,
4890
5127
  LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE11,
4891
5128
  Logger as Logger11
4892
5129
  } from "octagonal-wheels/common/logger";
@@ -4901,7 +5138,7 @@ function createInstanceLogFunction(serviceName, APIService2) {
4901
5138
  return;
4902
5139
  }
4903
5140
  let formattedMsg = typeof msg === "string" ? msg : isError ? msg.message : JSON.stringify(msg);
4904
- if (level < LOG_LEVEL_NOTICE4) {
5141
+ if (level < LOG_LEVEL_NOTICE5) {
4905
5142
  formattedMsg = `[${serviceName}]${MARK_LOG_SEPARATOR} ${formattedMsg}`;
4906
5143
  }
4907
5144
  logFunc(formattedMsg, level, key);
@@ -4978,6 +5215,7 @@ var LiveSyncManagers = class {
4978
5215
  });
4979
5216
  const chunkFetcher = new ChunkFetcher({
4980
5217
  chunkManager,
5218
+ source: this.options.chunkFetchSource,
4981
5219
  replicatorService: this.options.replicatorService,
4982
5220
  settingService: this.options.settingService
4983
5221
  });
@@ -5047,6 +5285,17 @@ function getNoFromRev(rev) {
5047
5285
  return parseInt(rev.split("-")[0]);
5048
5286
  }
5049
5287
  var LiveSyncLocalDB = class {
5288
+ constructor(dbname, env, runtimeOptions = {}) {
5289
+ this.runtimeOptions = runtimeOptions;
5290
+ this.auth = {
5291
+ username: "",
5292
+ password: ""
5293
+ };
5294
+ this.dbname = dbname;
5295
+ this.env = env;
5296
+ this._log = createInstanceLogFunction("LiveSyncLocalDB", this.env.services.API);
5297
+ this.refreshSettings();
5298
+ }
5050
5299
  auth;
5051
5300
  dbname;
5052
5301
  settings;
@@ -5078,16 +5327,6 @@ var LiveSyncLocalDB = class {
5078
5327
  /** Share owner retirement across every close path for one physical database lifetime. */
5079
5328
  activeReplicationClose;
5080
5329
  databaseUnloadNotification;
5081
- constructor(dbname, env) {
5082
- this.auth = {
5083
- username: "",
5084
- password: ""
5085
- };
5086
- this.dbname = dbname;
5087
- this.env = env;
5088
- this._log = createInstanceLogFunction("LiveSyncLocalDB", this.env.services.API);
5089
- this.refreshSettings();
5090
- }
5091
5330
  /** Notify dependent services at most once for each physical database lifecycle. */
5092
5331
  notifyDatabaseUnload() {
5093
5332
  if (!this.databaseUnloadNotification) {
@@ -5201,6 +5440,7 @@ var LiveSyncLocalDB = class {
5201
5440
  this.databaseUnloadNotification = void 0;
5202
5441
  const manager = new LiveSyncManagers({
5203
5442
  database: this.localDatabase,
5443
+ chunkFetchSource: this.runtimeOptions?.createChunkFetchSource?.(this.localDatabase),
5204
5444
  APIService: this.env.services.API,
5205
5445
  pathService: this.env.services.path,
5206
5446
  replicatorService: this.env.services.replicator,
@@ -5216,6 +5456,7 @@ var LiveSyncLocalDB = class {
5216
5456
  this._log("Database initialisation was rejected by a required module.", LOG_LEVEL_NOTICE);
5217
5457
  return false;
5218
5458
  }
5459
+ manager.changeManager.restartWatch();
5219
5460
  this._log("Opening Database...");
5220
5461
  this._log("Database info", LOG_LEVEL_VERBOSE);
5221
5462
  this._log(JSON.stringify(await openedDatabase.info(), null, 2), LOG_LEVEL_VERBOSE);
@@ -5604,13 +5845,155 @@ var MARK_SHIFT = `L`;
5604
5845
  var MARK_SHIFT_COMPRESSED = `${MARK_SHIFT}Z`;
5605
5846
 
5606
5847
  // lib/livesync-commonlib/src/pouchdb/encryption.ts
5607
- import { isPathProbablyObfuscated, obfuscatePath } from "octagonal-wheels/encryption/encryption";
5848
+ import { ENCRYPT_V2_PREFIX as ENCRYPT_V2_PREFIX2, isPathProbablyObfuscated, obfuscatePath } from "octagonal-wheels/encryption/encryption";
5849
+
5850
+ // lib/livesync-commonlib/src/pouchdb/encryption.policy.ts
5851
+ import {
5852
+ ENCRYPT_V1_PREFIX_PROBABLY,
5853
+ ENCRYPT_V2_PREFIX,
5854
+ ENCRYPT_V3_PREFIX
5855
+ } from "octagonal-wheels/encryption/encryption";
5856
+
5857
+ // lib/livesync-commonlib/src/pouchdb/encryption.eden.ts
5858
+ var EDEN_ENCRYPTED_KEY = "h:++encrypted";
5859
+ var EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
5860
+ function shouldEncryptEden(doc) {
5861
+ if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
5862
+ return true;
5863
+ }
5864
+ return false;
5865
+ }
5866
+ function shouldEncryptEdenHKDF(doc) {
5867
+ if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
5868
+ if (Object.keys(doc.eden).length === 0) {
5869
+ return false;
5870
+ }
5871
+ return true;
5872
+ }
5873
+ return false;
5874
+ }
5875
+ function shouldDecryptEden(doc) {
5876
+ if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
5877
+ return true;
5878
+ }
5879
+ return false;
5880
+ }
5881
+ function shouldDecryptEdenHKDF(doc) {
5882
+ if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
5883
+ return true;
5884
+ }
5885
+ return false;
5886
+ }
5887
+
5888
+ // lib/livesync-commonlib/src/pouchdb/encryption.policy.ts
5889
+ var METADATA_ONLY_ENTRY_TYPES = /* @__PURE__ */ new Set([
5890
+ EntryTypes.NOTE_BINARY,
5891
+ EntryTypes.NOTE_PLAIN,
5892
+ EntryTypes.INTERNAL_FILE
5893
+ ]);
5894
+ var ENCRYPTED_EDEN_KEYS = /* @__PURE__ */ new Set([EDEN_ENCRYPTED_KEY, EDEN_ENCRYPTED_KEY_HKDF]);
5895
+ var CONTROL_DOCUMENT_TYPES = /* @__PURE__ */ new Map([
5896
+ [DOCID_SYNC_PARAMETERS, EntryTypes.SYNC_PARAMETERS],
5897
+ [MILESTONE_DOCID, EntryTypes.MILESTONE_INFO],
5898
+ [NODEINFO_DOCID, EntryTypes.NODE_INFO],
5899
+ [SYNCINFO_ID, EntryTypes.SYNC_INFO],
5900
+ [VERSIONING_DOCID, EntryTypes.VERSION_INFO]
5901
+ ]);
5902
+ function hasReadableBody(value) {
5903
+ return value !== void 0;
5904
+ }
5905
+ function isEncryptedEdenKey(key, algorithm) {
5906
+ return key === EDEN_ENCRYPTED_KEY || key === EDEN_ENCRYPTED_KEY_HKDF && algorithm !== E2EEAlgorithms.ForceV1;
5907
+ }
5908
+ function hasPlaintextEden(record, algorithm) {
5909
+ const eden = record.eden;
5910
+ if (typeof eden !== "object" || eden === null) return false;
5911
+ const keys = Object.keys(eden);
5912
+ return keys.some((key) => !isEncryptedEdenKey(key, algorithm));
5913
+ }
5914
+ function hasUnsupportedEncryptedEden(record, algorithm) {
5915
+ const eden = record.eden;
5916
+ if (typeof eden !== "object" || eden === null) return false;
5917
+ return Object.keys(eden).some(
5918
+ (key) => ENCRYPTED_EDEN_KEYS.has(key) && !isEncryptedEdenKey(key, algorithm)
5919
+ );
5920
+ }
5921
+ function getUnencryptedContentKinds(doc, algorithm) {
5922
+ const record = doc;
5923
+ const documentId = typeof record._id === "string" ? record._id : "";
5924
+ const type = record.type;
5925
+ if (record._deleted === true || documentId.startsWith("_local/")) return [];
5926
+ const isChunkId = documentId.startsWith(IDPrefixes.Chunk);
5927
+ const expectedControlType = CONTROL_DOCUMENT_TYPES.get(documentId);
5928
+ const isControlDocument = expectedControlType !== void 0 && expectedControlType === type;
5929
+ if (!isChunkId && isControlDocument) return [];
5930
+ const isChunkBody = isChunkId || type === EntryTypes.CHUNK || type === EntryTypes.CHUNK_PACK;
5931
+ if (!isChunkBody && METADATA_ONLY_ENTRY_TYPES.has(type) && record.deleted === true) return [];
5932
+ const kinds = [];
5933
+ if (hasPlaintextEden(record, algorithm)) kinds.push("eden");
5934
+ if (hasReadableBody(record.data)) kinds.push(isChunkBody ? "chunk" : "inline-note");
5935
+ return kinds;
5936
+ }
5937
+ function isBase64Payload(value) {
5938
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
5939
+ }
5940
+ function hasForceV1CiphertextHeaderFor(data) {
5941
+ if (typeof data !== "string") return false;
5942
+ if (data.startsWith(ENCRYPT_V3_PREFIX)) {
5943
+ return /^[0-9a-f]{24}$/i.test(data.slice(2, 26)) && isBase64Payload(data.slice(26));
5944
+ }
5945
+ if (data.startsWith(ENCRYPT_V2_PREFIX)) {
5946
+ return /^[0-9a-f]{64}$/i.test(data.slice(1, 65)) && isBase64Payload(data.slice(65));
5947
+ }
5948
+ if (!data.startsWith(ENCRYPT_V1_PREFIX_PROBABLY) || !data.endsWith("]")) return false;
5949
+ try {
5950
+ const parsed = JSON.parse(data);
5951
+ if (!Array.isArray(parsed) || parsed.length !== 3 || !parsed.every((part) => typeof part === "string")) {
5952
+ return false;
5953
+ }
5954
+ const [ciphertext, iv, salt] = parsed;
5955
+ return isBase64Payload(ciphertext) && /^[0-9a-f]{32}$/i.test(iv) && /^[0-9a-f]{32}$/i.test(salt);
5956
+ } catch {
5957
+ return false;
5958
+ }
5959
+ }
5960
+ function assertUnencryptedContentPolicy(doc, algorithm, acceptUnencryptedContent, hasForceV1CiphertextHeader = false) {
5961
+ const contentKinds = getUnencryptedContentKinds(doc, algorithm);
5962
+ if (contentKinds.length === 0) return;
5963
+ const record = doc;
5964
+ if (hasUnsupportedEncryptedEden(record, algorithm)) {
5965
+ throw new Error("Encrypted Eden uses a representation which this E2EE reader cannot decrypt.");
5966
+ }
5967
+ const dataIsHandledByExistingDecryptor = isEncryptedChunkEntry(doc) || isSyncInfoEntry(doc);
5968
+ const forceV1DecryptsMarkedData = algorithm === E2EEAlgorithms.ForceV1 && (dataIsHandledByExistingDecryptor || isObfuscatedEntry(doc) || shouldDecryptEden(doc));
5969
+ for (const contentKind of contentKinds) {
5970
+ if (contentKind !== "eden" && record.e_ === true) {
5971
+ if (forceV1DecryptsMarkedData || dataIsHandledByExistingDecryptor) continue;
5972
+ throw new Error("Encrypted file content uses a representation which this E2EE reader cannot decrypt.");
5973
+ }
5974
+ if (contentKind === "chunk" && algorithm === E2EEAlgorithms.ForceV1 && !record.e_ && isEncryptedChunkEntry(doc) && hasForceV1CiphertextHeader) {
5975
+ continue;
5976
+ }
5977
+ if (!acceptUnencryptedContent) throw new UnencryptedContentRejectedError(doc._id, contentKind);
5978
+ }
5979
+ }
5980
+ function isEncryptedEntry(doc, hasForceV1CiphertextHeader) {
5981
+ const hasMarkedCiphertext = "e_" in doc && doc.e_ === true;
5982
+ const shouldDecryptData = isEncryptedChunkEntry(doc) || isSyncInfoEntry(doc) ? hasMarkedCiphertext || hasForceV1CiphertextHeader : (isObfuscatedEntry(doc) || shouldDecryptEden(doc)) && hasMarkedCiphertext;
5983
+ if (!shouldDecryptData) return false;
5984
+ if (!("data" in doc) || typeof doc.data !== "string") {
5985
+ throw new TypeError("Encrypted file content must be a string.");
5986
+ }
5987
+ return true;
5988
+ }
5989
+
5990
+ // lib/livesync-commonlib/src/pouchdb/encryption.ts
5608
5991
  var encrypt2 = encryptWorker;
5609
5992
  var decrypt2 = decryptWorker;
5610
5993
  var encryptHKDF2 = encryptHKDFWorker;
5611
5994
  var decryptHKDF2 = decryptHKDFWorker;
5612
5995
  var Encrypt_HKDF_Header = "%=";
5613
- var Encrypt_OLD_Header = "%";
5996
+ var Encrypt_OLD_Header = ENCRYPT_V2_PREFIX2;
5614
5997
  var EncryptionVersions = {
5615
5998
  UNENCRYPTED: 0,
5616
5999
  ENCRYPTED: 1,
@@ -5628,20 +6011,17 @@ function getEncryptionVersion(data) {
5628
6011
  }
5629
6012
  return EncryptionVersions.UNENCRYPTED;
5630
6013
  }
5631
- async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicIterationCount) {
6014
+ async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicIterationCount, log = logger_exports.Logger) {
5632
6015
  try {
5633
6016
  return await decrypt2(encryptedData, passphrase, useDynamicIterationCount);
5634
6017
  } catch (ex) {
5635
6018
  try {
5636
- (0, logger_exports.Logger)(
5637
- "Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",
5638
- logger_exports.LOG_LEVEL_VERBOSE
5639
- );
5640
- (0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
6019
+ log("Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.", logger_exports.LOG_LEVEL_VERBOSE);
6020
+ log(ex, logger_exports.LOG_LEVEL_VERBOSE);
5641
6021
  return await decrypt2(encryptedData, passphrase, false);
5642
6022
  } catch (ex2) {
5643
- (0, logger_exports.Logger)("Completely failed to decrypt with V1 method.", logger_exports.LOG_LEVEL_VERBOSE);
5644
- (0, logger_exports.Logger)(ex2, logger_exports.LOG_LEVEL_VERBOSE);
6023
+ log("Completely failed to decrypt with V1 method.", logger_exports.LOG_LEVEL_VERBOSE);
6024
+ log(ex2, logger_exports.LOG_LEVEL_VERBOSE);
5645
6025
  return false;
5646
6026
  }
5647
6027
  }
@@ -5651,9 +6031,7 @@ function isEncryptedMeta(doc) {
5651
6031
  return "path" in doc && doc.path.startsWith(ENCRYPTED_META_PREFIX);
5652
6032
  }
5653
6033
  function isInternalObfuscatedEntry(doc) {
5654
- return [ICHeader, ICXHeader, PSCHeader].some(
5655
- (prefix) => doc._id.startsWith(`${prefix}${PREFIX_OBFUSCATED}`)
5656
- );
6034
+ return [ICHeader, ICXHeader, PSCHeader].some((prefix) => doc._id.startsWith(`${prefix}${IDPrefixes.Obfuscated}`));
5657
6035
  }
5658
6036
  async function encryptMetaWithHKDF(doc, passphrase, pbkdf2Salt) {
5659
6037
  if (isEncryptedMeta(doc)) {
@@ -5749,10 +6127,11 @@ async function incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, ge
5749
6127
  }
5750
6128
  return saveDoc;
5751
6129
  }
5752
- async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt) {
6130
+ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt, log, algorithm, acceptUnencryptedContent) {
5753
6131
  const loadDoc = {
5754
6132
  ...doc
5755
6133
  };
6134
+ assertUnencryptedContentPolicy(loadDoc, algorithm, acceptUnencryptedContent);
5756
6135
  if (isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc)) {
5757
6136
  try {
5758
6137
  const encryptionVersion = getEncryptionVersion(loadDoc);
@@ -5761,21 +6140,26 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5761
6140
  loadDoc.data = await decryptHKDF2(loadDoc.data, passphrase, pbkdf2salt);
5762
6141
  delete loadDoc.e_;
5763
6142
  } else if (encryptionVersion === EncryptionVersions.ENCRYPTED) {
5764
- const decryptedData = await tryDecryptV1AsFallback(loadDoc.data, passphrase, useDynamicIterationCount);
6143
+ const decryptedData = await tryDecryptV1AsFallback(
6144
+ loadDoc.data,
6145
+ passphrase,
6146
+ useDynamicIterationCount,
6147
+ log
6148
+ );
5765
6149
  if (decryptedData === false) {
5766
- (0, logger_exports.Logger)(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
6150
+ log(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
5767
6151
  throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5768
6152
  }
5769
6153
  loadDoc.data = decryptedData;
5770
6154
  delete loadDoc.e_;
5771
6155
  } else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {
5772
6156
  } else {
5773
- (0, logger_exports.Logger)("Unknown encryption version. Cannot decrypt.", logger_exports.LOG_LEVEL_NOTICE);
6157
+ log("Unknown encryption version. Cannot decrypt.", logger_exports.LOG_LEVEL_NOTICE);
5774
6158
  throw new Error("Unknown encryption version. Cannot decrypt.");
5775
6159
  }
5776
6160
  } catch (ex) {
5777
- (0, logger_exports.Logger)(DECRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
5778
- (0, logger_exports.Logger)(ex);
6161
+ log(DECRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
6162
+ log(ex);
5779
6163
  throw ex;
5780
6164
  }
5781
6165
  }
@@ -5788,16 +6172,16 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5788
6172
  loadDoc[key] = metadata[key];
5789
6173
  }
5790
6174
  } catch (ex) {
5791
- (0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
5792
- (0, logger_exports.Logger)(ex);
6175
+ log(`${DECRYPTION_HKDF_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
6176
+ log(ex);
5793
6177
  throw ex;
5794
6178
  }
5795
6179
  } else {
5796
6180
  const path = getPath(loadDoc);
5797
6181
  if (isPathProbablyObfuscated(path)) {
5798
- const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
6182
+ const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount, log);
5799
6183
  if (decryptedPath === false) {
5800
- (0, logger_exports.Logger)(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
6184
+ log(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
5801
6185
  throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5802
6186
  }
5803
6187
  loadDoc.path = decryptedPath;
@@ -5811,7 +6195,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5811
6195
  const decryptedEden = await tryDecryptV1AsFallback(
5812
6196
  loadDoc.eden[EDEN_ENCRYPTED_KEY].data,
5813
6197
  passphrase,
5814
- useDynamicIterationCount
6198
+ useDynamicIterationCount,
6199
+ log
5815
6200
  );
5816
6201
  if (decryptedEden === false) throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5817
6202
  readEden = {
@@ -5820,8 +6205,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5820
6205
  };
5821
6206
  edenDecrypted = true;
5822
6207
  } catch (ex) {
5823
- (0, logger_exports.Logger)(`${DECRYPTION_FALLBACK_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
5824
- (0, logger_exports.Logger)(ex);
6208
+ log(`${DECRYPTION_FALLBACK_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
6209
+ log(ex);
5825
6210
  throw ex;
5826
6211
  }
5827
6212
  }
@@ -5839,8 +6224,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5839
6224
  };
5840
6225
  edenDecrypted = true;
5841
6226
  } catch (ex) {
5842
- (0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
5843
- (0, logger_exports.Logger)(ex);
6227
+ log(`${DECRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
6228
+ log(ex);
5844
6229
  throw ex;
5845
6230
  }
5846
6231
  }
@@ -5892,28 +6277,30 @@ async function incomingEncryptV1(doc, passphrase, useDynamicIterationCount) {
5892
6277
  }
5893
6278
  return saveDoc;
5894
6279
  }
5895
- async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount) {
6280
+ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, log, acceptUnencryptedContent) {
5896
6281
  const loadDoc = {
5897
6282
  ...doc
5898
6283
  };
5899
6284
  const _isChunkOrSyncInfo = isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc);
5900
6285
  const _isObfuscatedEntry = isObfuscatedEntry(loadDoc);
5901
6286
  const _shouldDecryptEden = shouldDecryptEden(loadDoc);
5902
- if (_isChunkOrSyncInfo || _isObfuscatedEntry || _shouldDecryptEden) {
6287
+ const hasMarkedCiphertext = "e_" in loadDoc && loadDoc.e_ === true;
6288
+ const hasForceV1CiphertextHeader = _isChunkOrSyncInfo && !hasMarkedCiphertext && hasForceV1CiphertextHeaderFor(loadDoc.data);
6289
+ assertUnencryptedContentPolicy(
6290
+ loadDoc,
6291
+ E2EEAlgorithms.ForceV1,
6292
+ acceptUnencryptedContent,
6293
+ hasForceV1CiphertextHeader
6294
+ );
6295
+ const _shouldDecryptData = isEncryptedEntry(loadDoc, hasForceV1CiphertextHeader);
6296
+ if (_shouldDecryptData || _isObfuscatedEntry || _shouldDecryptEden) {
5903
6297
  if (migrationDecrypt && decrypted.has(loadDoc._id)) {
5904
6298
  return loadDoc;
5905
6299
  }
5906
6300
  try {
5907
- if (_isChunkOrSyncInfo) {
6301
+ if (_shouldDecryptData) {
5908
6302
  loadDoc.data = await decrypt2(loadDoc.data, passphrase, useDynamicIterationCount);
5909
- delete loadDoc.e_;
5910
- } else if ("e_" in loadDoc) {
5911
- loadDoc.data = await decrypt2(
5912
- loadDoc.data,
5913
- passphrase,
5914
- useDynamicIterationCount
5915
- );
5916
- delete loadDoc.e_;
6303
+ if ("e_" in loadDoc) delete loadDoc.e_;
5917
6304
  }
5918
6305
  if (_isObfuscatedEntry) {
5919
6306
  const path = getPath(loadDoc);
@@ -5936,7 +6323,7 @@ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, u
5936
6323
  } catch (ex) {
5937
6324
  if (useDynamicIterationCount) {
5938
6325
  try {
5939
- if (_isChunkOrSyncInfo) {
6326
+ if (_shouldDecryptData) {
5940
6327
  loadDoc.data = await decrypt2(loadDoc.data, passphrase, false);
5941
6328
  }
5942
6329
  if (_isObfuscatedEntry) {
@@ -5957,15 +6344,15 @@ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, u
5957
6344
  if (migrationDecrypt && ex2 instanceof SyntaxError) {
5958
6345
  return loadDoc;
5959
6346
  }
5960
- (0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
5961
- (0, logger_exports.Logger)(ex2, logger_exports.LOG_LEVEL_VERBOSE);
5962
- (0, logger_exports.Logger)(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
6347
+ log("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
6348
+ log(ex2, logger_exports.LOG_LEVEL_VERBOSE);
6349
+ log(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
5963
6350
  throw ex2;
5964
6351
  }
5965
6352
  } else {
5966
- (0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
5967
- (0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
5968
- (0, logger_exports.Logger)(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
6353
+ log("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
6354
+ log(ex, logger_exports.LOG_LEVEL_VERBOSE);
6355
+ log(`id:${loadDoc._id}-${loadDoc._rev?.substring(0, 10)}`, logger_exports.LOG_LEVEL_VERBOSE);
5969
6356
  throw ex;
5970
6357
  }
5971
6358
  }
@@ -5978,8 +6365,9 @@ var preprocessOutgoing = async (doc) => {
5978
6365
  var preprocessIncoming = async (doc) => {
5979
6366
  return await Promise.resolve(doc);
5980
6367
  };
5981
- function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false) {
6368
+ function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, log = logger_exports.Logger, acceptUnencryptedContent = false) {
5982
6369
  const decryptedCache = /* @__PURE__ */ new Map();
6370
+ const acceptUnencrypted = normaliseAcceptUnencryptedContent(acceptUnencryptedContent);
5983
6371
  const incoming = (doc) => algorithm === E2EEAlgorithms.V2 ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt, encryptInternalMetadata) : incomingEncryptV1(doc, passphrase, useDynamicIterationCount);
5984
6372
  const outgoing = (doc) => algorithm !== E2EEAlgorithms.ForceV1 ? outgoingDecryptHKDF(
5985
6373
  doc,
@@ -5987,21 +6375,34 @@ function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCoun
5987
6375
  decryptedCache,
5988
6376
  passphrase,
5989
6377
  useDynamicIterationCount,
5990
- getPBKDF2Salt
5991
- ) : outgoingDecryptV1(doc, migrationDecrypt, decryptedCache, passphrase, useDynamicIterationCount);
6378
+ getPBKDF2Salt,
6379
+ log,
6380
+ algorithm,
6381
+ acceptUnencrypted
6382
+ ) : outgoingDecryptV1(
6383
+ doc,
6384
+ migrationDecrypt,
6385
+ decryptedCache,
6386
+ passphrase,
6387
+ useDynamicIterationCount,
6388
+ log,
6389
+ acceptUnencrypted
6390
+ );
5992
6391
  return {
5993
6392
  incoming,
5994
6393
  outgoing
5995
6394
  };
5996
6395
  }
5997
- var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false) => {
6396
+ var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, acceptUnencryptedContent = false) => {
5998
6397
  const { incoming, outgoing } = getConfiguredFunctionsForEncryption(
5999
6398
  passphrase,
6000
6399
  useDynamicIterationCount,
6001
6400
  migrationDecrypt,
6002
6401
  getPBKDF2Salt,
6003
6402
  algorithm,
6004
- encryptInternalMetadata
6403
+ encryptInternalMetadata,
6404
+ logger_exports.Logger,
6405
+ acceptUnencryptedContent
6005
6406
  );
6006
6407
  db.transform({
6007
6408
  incoming,
@@ -6016,44 +6417,15 @@ function disableEncryption() {
6016
6417
  return await Promise.resolve(doc);
6017
6418
  };
6018
6419
  }
6019
- var EDEN_ENCRYPTED_KEY = "h:++encrypted";
6020
- var EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
6021
- function shouldEncryptEden(doc) {
6022
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
6023
- return true;
6024
- }
6025
- return false;
6026
- }
6027
- function shouldEncryptEdenHKDF(doc) {
6028
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
6029
- if (Object.keys(doc.eden).length === 0) {
6030
- return false;
6031
- }
6032
- return true;
6033
- }
6034
- return false;
6035
- }
6036
- function shouldDecryptEden(doc) {
6037
- if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
6038
- return true;
6039
- }
6040
- return false;
6041
- }
6042
- function shouldDecryptEdenHKDF(doc) {
6043
- if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
6044
- return true;
6045
- }
6046
- return false;
6047
- }
6048
6420
 
6049
6421
  // lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
6050
6422
  import {
6051
- LEVEL_INFO as LEVEL_INFO2,
6052
- LEVEL_VERBOSE,
6423
+ LEVEL_INFO as LEVEL_INFO3,
6424
+ LEVEL_VERBOSE as LEVEL_VERBOSE2,
6053
6425
  LOG_LEVEL_INFO as LOG_LEVEL_INFO6,
6054
- LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE9,
6426
+ LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE10,
6055
6427
  LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE21,
6056
- Logger as Logger19
6428
+ Logger as Logger20
6057
6429
  } from "octagonal-wheels/common/logger";
6058
6430
  import { promiseWithResolvers as promiseWithResolvers8 } from "octagonal-wheels/promises";
6059
6431
 
@@ -6190,6 +6562,7 @@ var Binder = class {
6190
6562
  }
6191
6563
  }
6192
6564
  _callback = null;
6565
+ _registrationToken = null;
6193
6566
  /**
6194
6567
  * Assigns a new handler function.
6195
6568
  * @param callback The new handler function to assign.
@@ -6198,8 +6571,14 @@ var Binder = class {
6198
6571
  if (this._callback && !override) {
6199
6572
  throw new Error(`Handler ${this._name} is already assigned.`);
6200
6573
  }
6574
+ const registrationToken = /* @__PURE__ */ Symbol();
6575
+ this._registrationToken = registrationToken;
6201
6576
  this._callback = callback;
6202
6577
  return () => {
6578
+ if (this._registrationToken !== registrationToken) {
6579
+ return;
6580
+ }
6581
+ this._registrationToken = null;
6203
6582
  this._callback = null;
6204
6583
  };
6205
6584
  }
@@ -6219,6 +6598,7 @@ var LazyBinder = class {
6219
6598
  _name;
6220
6599
  _callbackPromise = promiseWithResolvers6();
6221
6600
  _callback = null;
6601
+ _registrationToken = null;
6222
6602
  /**
6223
6603
  * Creates a new LazyBinder instance.
6224
6604
  * @param name The name of the handler.
@@ -6235,9 +6615,15 @@ var LazyBinder = class {
6235
6615
  if (this._callback && !override) {
6236
6616
  throw new Error(`Handler ${this._name} is already assigned.`);
6237
6617
  }
6618
+ const registrationToken = /* @__PURE__ */ Symbol();
6619
+ this._registrationToken = registrationToken;
6238
6620
  this._callback = callback;
6239
6621
  this._callbackPromise.resolve();
6240
6622
  return () => {
6623
+ if (this._registrationToken !== registrationToken) {
6624
+ return;
6625
+ }
6626
+ this._registrationToken = null;
6241
6627
  this._callback = null;
6242
6628
  this._callbackPromise = promiseWithResolvers6();
6243
6629
  };
@@ -6481,6 +6867,30 @@ var FirstResultHandler = class extends MultiBinder {
6481
6867
  return false;
6482
6868
  }
6483
6869
  };
6870
+ var FirstHandledHandler = class extends MultiBinder {
6871
+ /**
6872
+ * Whether at least one callback is currently registered.
6873
+ */
6874
+ get hasHandlers() {
6875
+ return this._callbackMap.size > 0;
6876
+ }
6877
+ /**
6878
+ * Invokes handlers until one returns a completed or veto outcome.
6879
+ * @param args The arguments to pass to the handlers.
6880
+ * @returns The first handled outcome, or a not-applicable outcome when no handler applies.
6881
+ * @throws Any synchronous callback error or rejected callback value, unchanged.
6882
+ */
6883
+ async invoke(...args) {
6884
+ const callbacks = [...this._callbacks];
6885
+ for (const callback of callbacks) {
6886
+ const outcome = await Promise.resolve(callback(...args));
6887
+ if (outcome.kind !== "not-applicable") {
6888
+ return outcome;
6889
+ }
6890
+ }
6891
+ return { kind: "not-applicable" };
6892
+ }
6893
+ };
6484
6894
  function getMultipleBound(handler) {
6485
6895
  const _handler = "invoke" in handler ? handler.invoke : handler.dispatch;
6486
6896
  const __handler = _handler.bind(handler);
@@ -6522,6 +6932,17 @@ function firstResultFunction(name) {
6522
6932
  const handler = new FirstResultHandler(name ?? "firstResultFunction");
6523
6933
  return getMultipleBound(handler);
6524
6934
  }
6935
+ function firstHandledFunction(name) {
6936
+ const handler = new FirstHandledHandler(
6937
+ name ?? "firstHandledFunction"
6938
+ );
6939
+ const toHandlerCallback = (callback) => callback;
6940
+ const bound = (...args) => handler.invoke(...args);
6941
+ bound.addHandler = (callback, priority) => handler.addHandler(toHandlerCallback(callback), priority);
6942
+ bound.removeHandler = (callback) => handler.removeHandler(toHandlerCallback(callback));
6943
+ Object.defineProperty(bound, "hasHandlers", { get: () => handler.hasHandlers });
6944
+ return bound;
6945
+ }
6525
6946
  function dispatchParallelFunction(name) {
6526
6947
  const handler = new DispatchParallel(
6527
6948
  name ?? "dispatchParallelFunction"
@@ -6607,6 +7028,15 @@ function handlers() {
6607
7028
  firstResult(name) {
6608
7029
  return firstResultFunction(String(name));
6609
7030
  },
7031
+ /**
7032
+ * Create a handler that invokes registered handlers until one completes or vetoes.
7033
+ * Callback errors and rejections propagate unchanged.
7034
+ * @param name The name of the callback on `T`.
7035
+ * @returns A bound handler with a live `hasHandlers` property.
7036
+ */
7037
+ firstHandled(name) {
7038
+ return firstHandledFunction(String(name));
7039
+ },
6610
7040
  /**
6611
7041
  * Create a handler that invokes all added handler functions in parallel.
6612
7042
  * @param name
@@ -6637,6 +7067,13 @@ function createLiveSyncEventHub() {
6637
7067
 
6638
7068
  // lib/livesync-commonlib/src/services/base/CommonlibMessages.ts
6639
7069
  var commonlibEnglishMessages = {
7070
+ "SettingService.ConfigurationPassphraseDeviceLocalDescription": "This passphrase stays on this device. When another device needs to decrypt protected settings without a saved key, enter the same passphrase at start-up.",
7071
+ "SettingService.ConfigurationPassphraseTitle": "Configuration passphrase",
7072
+ "SettingService.ConfigurationPassphraseRetryTitle": "Configuration could not be decrypted. Enter the configuration passphrase again.",
7073
+ "SettingService.ConfigurationPassphraseCancelled": "Configuration passphrase entry was cancelled or unavailable. Start-up was stopped; saved settings were retained.",
7074
+ "SettingService.ConfigurationEncryptionSaveFailed": "Configuration encryption could not be saved. Verify the saved settings and device key before retrying.",
7075
+ "SettingService.ConfigurationPassphraseRollbackFailed": "The configuration passphrase could not be restored after a write failure. Verify the saved settings and device key before retrying.",
7076
+ "SettingService.ConfigurationCouldNotBeDecrypted": "Existing configuration could not be decrypted. The configuration key was not changed.",
6640
7077
  "(BETA) Always overwrite with a newer file": "(BETA) Always overwrite with a newer file",
6641
7078
  "(Beta) Use ignore files": "(Beta) Use ignore files",
6642
7079
  "(Days passed, 0 to disable automatic-deletion)": "(Days passed, 0 to disable automatic-deletion)",
@@ -7047,7 +7484,7 @@ var AppLifecycleService = class extends ServiceBase {
7047
7484
  * Event triggered before the plug-in is unloaded.
7048
7485
  * This is typically used to perform any necessary cleanup or save state before the plug-in is unloaded.
7049
7486
  */
7050
- onBeforeUnload = handlers().all("onBeforeUnload");
7487
+ onBeforeUnload = handlers().allSettled("onBeforeUnload");
7051
7488
  /**
7052
7489
  * Event triggered when the plug-in is being unloaded.
7053
7490
  *
@@ -7203,10 +7640,18 @@ var FileProcessingService = class extends ServiceBase {
7203
7640
  */
7204
7641
  processFileEvent = handlers().anySuccess("processFileEvent");
7205
7642
  /**
7206
- * Process a file event item optionally, if any handler is registered.
7643
+ * Dispatch a legacy optional notification, without confirming persistence.
7207
7644
  * i.e., hidden files synchronisation or customisation sync.
7208
7645
  */
7209
7646
  processOptionalFileEvent = handlers().anySuccess("processOptionalFileEvent");
7647
+ /**
7648
+ * Complete optional file operations through the first applicable handler.
7649
+ * Hosts migrate all optional providers together. Once any typed provider is
7650
+ * registered, dispatch uses this contract exclusively.
7651
+ */
7652
+ processOptionalFileEventWithResult = handlers().firstHandled(
7653
+ "processOptionalFileEventWithResult"
7654
+ );
7210
7655
  /**
7211
7656
  * Commit any pending file events that have been queued for processing.
7212
7657
  */
@@ -7249,9 +7694,9 @@ var PathService = class extends ServiceBase {
7249
7694
  const [prefix, path] = expandFilePathPrefix(filename);
7250
7695
  return prefix + this.normalizePath(path);
7251
7696
  }
7252
- async _path2id(filename, obfuscatePassphrase, caseInsensitive, idDerivationKey) {
7697
+ async _path2id(filename, obfuscatePassphrase, caseInsensitive, idDerivationKey, pathNormalizationVersion) {
7253
7698
  const [prefix, path] = expandFilePathPrefix(filename);
7254
- const fixedPath = prefix + this.normalizePath(path);
7699
+ const fixedPath = prefix + normalisePathForIdentity(this.normalizePath(path), pathNormalizationVersion);
7255
7700
  const out = await path2id_base(fixedPath, obfuscatePassphrase, caseInsensitive, idDerivationKey);
7256
7701
  return out;
7257
7702
  }
@@ -7280,13 +7725,15 @@ var PathService = class extends ServiceBase {
7280
7725
  }
7281
7726
  /** Convert a path using the caller's settings snapshot and this host's path normalisation. */
7282
7727
  async path2idWithSettings(filename, setting, prefix) {
7728
+ const pathNormalizationVersion = getPathNormalizationVersion(setting);
7283
7729
  const destPath = addPrefix(filename, prefix ?? "");
7284
7730
  const pathObfuscationPassphrase = this.getPathObfuscationPassphrase?.() ?? (setting.usePathObfuscation ? setting.passphrase : false);
7285
7731
  return await this._path2id(
7286
7732
  destPath,
7287
7733
  pathObfuscationPassphrase,
7288
7734
  !setting.handleFilenameCaseSensitive,
7289
- setting.encrypt && configuredIdKey(setting) || void 0
7735
+ setting.encrypt && configuredIdKey(setting) || void 0,
7736
+ pathNormalizationVersion
7290
7737
  );
7291
7738
  }
7292
7739
  getPath(entry) {
@@ -7537,6 +7984,40 @@ async function runWithTrackedPhysicalRequest(counters, task) {
7537
7984
  }
7538
7985
  }
7539
7986
 
7987
+ // lib/livesync-commonlib/src/services/lib/couchdbHttpCache.ts
7988
+ var processEpoch = Math.floor(Date.now() / 1e3);
7989
+ function createCouchDBHttpCache(uri, getPBKDF2Salt, headersOnly = false) {
7990
+ const databasePath = new URL(uri).pathname.replace(/\/$/, "");
7991
+ let previousSalt;
7992
+ let namespace;
7993
+ const getNamespace = async () => {
7994
+ const salt = await getPBKDF2Salt();
7995
+ if (!previousSalt || previousSalt.length !== salt.length || previousSalt.some((byte, i) => byte !== salt[i])) {
7996
+ previousSalt = salt.slice();
7997
+ const epoch = new TextEncoder().encode(`${processEpoch}:`);
7998
+ const input = new Uint8Array(epoch.length + previousSalt.length);
7999
+ input.set(epoch);
8000
+ input.set(previousSalt, epoch.length);
8001
+ namespace = crypto.subtle.digest("SHA-256", input).then((digest) => uint8ArrayToHexString(new Uint8Array(digest)));
8002
+ }
8003
+ return namespace;
8004
+ };
8005
+ return async (request, options) => {
8006
+ const method = (options?.method ?? (typeof request === "string" ? "GET" : request.method)).toUpperCase();
8007
+ if (method !== "GET" && method !== "HEAD") {
8008
+ return { request, cache: options?.cache };
8009
+ }
8010
+ if (headersOnly) return { request, cache: "no-store" };
8011
+ const url = new URL(typeof request === "string" ? request : request.url);
8012
+ const relativePath = url.pathname.startsWith(`${databasePath}/`) ? decodeURIComponent(url.pathname.slice(databasePath.length + 1)) : "";
8013
+ if (getPBKDF2Salt && relativePath && !relativePath.startsWith("_local/")) {
8014
+ url.searchParams.set("_livesync_epoch", await getNamespace());
8015
+ request = typeof request === "string" ? url.href : new Request(url.href, request);
8016
+ }
8017
+ return { request, cache: "no-cache" };
8018
+ };
8019
+ }
8020
+
7540
8021
  // lib/livesync-commonlib/src/services/base/RemoteService.ts
7541
8022
  function createRemoteConnectionScope(ownerSignal) {
7542
8023
  const controller = new AbortController();
@@ -7713,6 +8194,12 @@ var RemoteService = class extends ServiceBase {
7713
8194
  return "Network is offline";
7714
8195
  }
7715
8196
  const connectionScope = createRemoteConnectionScope(connectionOptions.signal);
8197
+ const encryptionAlgorithm = connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;
8198
+ const prepareCachedRequest = createCouchDBHttpCache(
8199
+ uri,
8200
+ typeof passphrase === "string" && passphrase !== "false" && encryptionAlgorithm !== E2EEAlgorithms.ForceV1 ? getPBKDF2Salt : void 0,
8201
+ connectionOptions.useCouchDBCacheControlHeadersOnly === true
8202
+ );
7716
8203
  const conf = {
7717
8204
  adapter: "http",
7718
8205
  auth: "username" in auth ? auth : void 0,
@@ -7747,11 +8234,12 @@ var RemoteService = class extends ServiceBase {
7747
8234
  if (!("username" in auth)) {
7748
8235
  headers.append("authorization", authHeader);
7749
8236
  }
8237
+ const cachedRequest = await prepareCachedRequest(requestSrc, opts);
7750
8238
  try {
7751
8239
  const signal = connectionScope.combine(opts?.signal);
7752
8240
  const response = await this.performFetch(
7753
- requestSrc,
7754
- { ...opts, headers, signal },
8241
+ cachedRequest.request,
8242
+ { ...opts, headers, signal, cache: cachedRequest.cache },
7755
8243
  useRequestAPI ? FetchMethod.native : FetchMethod.webCompat
7756
8244
  );
7757
8245
  return response;
@@ -7767,7 +8255,11 @@ var RemoteService = class extends ServiceBase {
7767
8255
  this._log(
7768
8256
  "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
7769
8257
  );
7770
- const resp2 = await this.performFetch(requestSrc, { ...opts, headers }, FetchMethod.native);
8258
+ const resp2 = await this.performFetch(
8259
+ cachedRequest.request,
8260
+ { ...opts, headers, cache: cachedRequest.cache },
8261
+ FetchMethod.native
8262
+ );
7771
8263
  if (resp2.status / 100 == 2) {
7772
8264
  this.showError(
7773
8265
  "The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",
@@ -7800,7 +8292,6 @@ var RemoteService = class extends ServiceBase {
7800
8292
  }
7801
8293
  }
7802
8294
  };
7803
- const encryptionAlgorithm = connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;
7804
8295
  let db;
7805
8296
  try {
7806
8297
  db = new this._pouchDB(uri, conf);
@@ -7829,7 +8320,8 @@ var RemoteService = class extends ServiceBase {
7829
8320
  false,
7830
8321
  getPBKDF2Salt,
7831
8322
  encryptionAlgorithm,
7832
- connectionOptions.encryptInternalMetadata ?? false
8323
+ connectionOptions.encryptInternalMetadata ?? false,
8324
+ connectionOptions.acceptUnencryptedContent ?? false
7833
8325
  );
7834
8326
  }
7835
8327
  } catch (ex) {
@@ -8773,7 +9265,7 @@ var ActiveReplicatorState = class {
8773
9265
  // lib/livesync-commonlib/src/services/base/ReplicatorService.remoteResourceResolver.ts
8774
9266
  async function resolveRemoteResource(capabilities, kind, setting) {
8775
9267
  const capability = capabilities[kind];
8776
- if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
9268
+ if (capability?.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
8777
9269
  return void 0;
8778
9270
  }
8779
9271
  return await capability.run(setting);
@@ -9318,30 +9810,6 @@ var InjectableVaultServiceCompat = class extends InjectableVaultService {
9318
9810
  }
9319
9811
  };
9320
9812
 
9321
- // lib/livesync-commonlib/src/services/base/ConfigService.ts
9322
- var ConfigService = class extends ServiceBase {
9323
- };
9324
-
9325
- // lib/livesync-commonlib/src/services/implements/browser/ConfigServiceBrowserCompat.ts
9326
- var ConfigServiceBrowserCompat = class extends ConfigService {
9327
- _settingService;
9328
- _log;
9329
- constructor(context, dependencies) {
9330
- super(context);
9331
- this._settingService = dependencies.settingService;
9332
- this._log = createInstanceLogFunction("ConfigService", dependencies.APIService);
9333
- }
9334
- getSmallConfig(key) {
9335
- return this._settingService.getSmallConfig(key);
9336
- }
9337
- setSmallConfig(key, value) {
9338
- return this._settingService.setSmallConfig(key, value);
9339
- }
9340
- deleteSmallConfig(key) {
9341
- return this._settingService.deleteSmallConfig(key);
9342
- }
9343
- };
9344
-
9345
9813
  // lib/livesync-commonlib/src/services/base/ControlService.ts
9346
9814
  import { LOG_LEVEL_URGENT as LOG_LEVEL_URGENT2 } from "octagonal-wheels/common/logger";
9347
9815
  import { cancelAllPeriodicTask, cancelAllTasks } from "octagonal-wheels/concurrency/task";
@@ -9382,7 +9850,9 @@ var ControlService = class extends ServiceBase {
9382
9850
  await this.services.appLifecycleService.onSuspending();
9383
9851
  await this.services.settingService.onBeforeRealiseSetting();
9384
9852
  this.services.databaseService.localDatabase.refreshSettings();
9385
- await this.services.fileProcessingService.commitPendingFileEvents();
9853
+ if (!await this.services.fileProcessingService.commitPendingFileEvents()) {
9854
+ throw new Error("Pending local file operations could not be completed before applying settings");
9855
+ }
9386
9856
  await this.services.settingService.onRealiseSetting();
9387
9857
  if (this.services.appLifecycleService.isSuspended()) return;
9388
9858
  await this.services.appLifecycleService.onResuming();
@@ -9391,7 +9861,8 @@ var ControlService = class extends ServiceBase {
9391
9861
  }
9392
9862
  async _onLiveSyncUnload() {
9393
9863
  this.context.events.emitEvent(EVENT_PLUGIN_UNLOADED);
9394
- await this.services.appLifecycleService.onBeforeUnload();
9864
+ const prepared = await this.services.appLifecycleService.onBeforeUnload();
9865
+ if (!prepared) this._log("Unload preparation failed; pending storage work may require recovery", LOG_LEVEL_URGENT2);
9395
9866
  await Promise.resolve(this.services.appLifecycleService.onAppUnload());
9396
9867
  cancelAllPeriodicTask();
9397
9868
  cancelAllTasks();
@@ -9406,6 +9877,7 @@ var ControlService = class extends ServiceBase {
9406
9877
  this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);
9407
9878
  this.context.events.offAll();
9408
9879
  this._log(this.context.translate("moduleLiveSyncMain.logUnloadingPlugin"));
9880
+ if (!prepared) throw new Error("Unload preparation failed");
9409
9881
  return;
9410
9882
  }
9411
9883
  /**
@@ -9613,12 +10085,67 @@ var InjectableServiceHub = class extends ServiceHub {
9613
10085
  }
9614
10086
  };
9615
10087
 
10088
+ // lib/livesync-commonlib/src/uiCommands.ts
10089
+ var UICommandRegistry = class {
10090
+ definitions = /* @__PURE__ */ new Map();
10091
+ handlers = /* @__PURE__ */ new Map();
10092
+ disposed = false;
10093
+ register(command, handler) {
10094
+ if (this.disposed) {
10095
+ throw new Error("Cannot register a UI command on a disposed registry");
10096
+ }
10097
+ const knownDefinition = this.definitions.get(command.id);
10098
+ if (knownDefinition !== void 0 && knownDefinition !== command) {
10099
+ throw new Error(`A conflicting command definition is already known for '${command.id}'`);
10100
+ }
10101
+ if (this.handlers.has(command.id)) {
10102
+ throw new Error(`A handler is already registered for '${command.id}'`);
10103
+ }
10104
+ this.definitions.set(command.id, command);
10105
+ const entry = {
10106
+ command,
10107
+ handler: (input) => handler(input)
10108
+ };
10109
+ this.handlers.set(command.id, entry);
10110
+ let active = true;
10111
+ return () => {
10112
+ if (!active) return;
10113
+ active = false;
10114
+ if (this.handlers.get(command.id) === entry) {
10115
+ this.handlers.delete(command.id);
10116
+ }
10117
+ };
10118
+ }
10119
+ async invoke(command, input) {
10120
+ if (this.disposed) {
10121
+ return { status: "unavailable" };
10122
+ }
10123
+ const entry = this.handlers.get(command.id);
10124
+ if (entry === void 0 || entry.command !== command) {
10125
+ return { status: "unavailable" };
10126
+ }
10127
+ return {
10128
+ status: "handled",
10129
+ value: await entry.handler(input)
10130
+ };
10131
+ }
10132
+ dispose() {
10133
+ if (this.disposed) return;
10134
+ this.disposed = true;
10135
+ this.handlers.clear();
10136
+ this.definitions.clear();
10137
+ }
10138
+ };
10139
+
9616
10140
  // lib/livesync-commonlib/src/services/implements/base/UIService.ts
9617
10141
  var UIService = class extends ServiceBase {
10142
+ commands;
9618
10143
  _dialogManager;
9619
10144
  _APIService;
9620
10145
  constructor(context, dependents) {
9621
10146
  super(context);
10147
+ this.commands = new UICommandRegistry();
10148
+ this.context.events.once(EVENT_PLUGIN_UNLOADED, () => this.commands.dispose());
9622
10149
  this._dialogManager = dependents.dialogManager;
9623
10150
  this._APIService = dependents.APIService;
9624
10151
  }
@@ -9658,6 +10185,18 @@ var APIService = class extends ServiceBase {
9658
10185
  showWindowOnRight(type) {
9659
10186
  return this.showWindow(type);
9660
10187
  }
10188
+ /**
10189
+ * Register synchronous cleanup for this host's normal terminal unload.
10190
+ * The default uses the context-owned platform-unloaded event once per registration,
10191
+ * after lifecycle handlers and local database closure. An unload interrupted before
10192
+ * that event does not execute these callbacks.
10193
+ * Native hosts may override this to retain their own unload timing. Callbacks are
10194
+ * not awaited; resource retirement which must finish before database closure
10195
+ * belongs to AppLifecycleService.onUnload instead.
10196
+ */
10197
+ registerCleanup(callback) {
10198
+ this.context.events.onceEvent(EVENT_PLATFORM_UNLOADED, callback);
10199
+ }
9661
10200
  requestCount = reactiveSource6(0);
9662
10201
  responseCount = reactiveSource6(0);
9663
10202
  get isOnline() {
@@ -9929,6 +10468,15 @@ var KeyValueDBService = class extends ServiceBase {
9929
10468
  this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this));
9930
10469
  }
9931
10470
  }
10471
+ /**
10472
+ * Create an inert namespaced handle over the service's current database.
10473
+ * @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
10474
+ * @returns A handle whose operations resolve the current database when invoked.
10475
+ * @remarks Construction performs no database I/O. Operations fail if the store
10476
+ * is not ready. For keys, an undefined upper bound means the complete remaining
10477
+ * namespace, including Unicode and empty keys. Explicit bounds are inclusive,
10478
+ * and the optional count is passed to the database unchanged.
10479
+ */
9932
10480
  openSimpleStore(kind) {
9933
10481
  const getDB = () => {
9934
10482
  if (!this._kvDB) {
@@ -9948,8 +10496,9 @@ var KeyValueDBService = class extends ServiceBase {
9948
10496
  await getDB().del(`${prefix}${key}`);
9949
10497
  },
9950
10498
  keys: async (from, to, count) => {
10499
+ const upperBound = to === void 0 ? `${prefix.slice(0, -1)}.` : `${prefix}${to || ""}`;
9951
10500
  const ret = await getDB().keys(
9952
- IDBKeyRange.bound(`${prefix}${from || ""}`, `${prefix}${to || ""}`),
10501
+ IDBKeyRange.bound(`${prefix}${from || ""}`, upperBound, false, to === void 0),
9953
10502
  count
9954
10503
  );
9955
10504
  return ret.map((e) => (typeof e === "string" ? e : JSON.stringify(e)).toString()).filter((e) => e.startsWith(prefix)).map((e) => e.substring(prefix.length));
@@ -10095,12 +10644,15 @@ var HeadlessDatabaseService = class extends DatabaseService {
10095
10644
  var HeadlessKeyValueDBService = class extends KeyValueDBService {
10096
10645
  };
10097
10646
 
10647
+ // lib/livesync-commonlib/src/services/base/SettingService.ts
10648
+ import { createDeletableValueStore } from "@vrtmrz/value-store";
10649
+
10098
10650
  // lib/livesync-commonlib/src/encryption/stringEncryption.ts
10099
10651
  import {
10100
10652
  decrypt as decrypt3,
10101
- ENCRYPT_V2_PREFIX,
10102
- ENCRYPT_V3_PREFIX,
10103
- ENCRYPT_V1_PREFIX_PROBABLY
10653
+ ENCRYPT_V2_PREFIX as ENCRYPT_V2_PREFIX3,
10654
+ ENCRYPT_V3_PREFIX as ENCRYPT_V3_PREFIX2,
10655
+ ENCRYPT_V1_PREFIX_PROBABLY as ENCRYPT_V1_PREFIX_PROBABLY2
10104
10656
  } from "octagonal-wheels/encryption/encryption";
10105
10657
  import {
10106
10658
  encryptWithEphemeralSalt,
@@ -10108,7 +10660,7 @@ import {
10108
10660
  HKDF_SALTED_ENCRYPTED_PREFIX
10109
10661
  } from "octagonal-wheels/encryption/hkdf";
10110
10662
  async function encryptString(source, passphrase) {
10111
- if (source.startsWith(ENCRYPT_V2_PREFIX)) {
10663
+ if (source.startsWith(ENCRYPT_V2_PREFIX3)) {
10112
10664
  return source;
10113
10665
  } else if (source.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {
10114
10666
  return source;
@@ -10130,7 +10682,7 @@ async function tryDecryption(trials) {
10130
10682
  async function decryptString(encrypted, passphrase) {
10131
10683
  if (encrypted.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {
10132
10684
  return decryptWithEphemeralSalt(encrypted, passphrase);
10133
- } else if (encrypted.startsWith(ENCRYPT_V2_PREFIX) || encrypted.startsWith(ENCRYPT_V3_PREFIX) || encrypted.startsWith(ENCRYPT_V1_PREFIX_PROBABLY)) {
10685
+ } else if (encrypted.startsWith(ENCRYPT_V2_PREFIX3) || encrypted.startsWith(ENCRYPT_V3_PREFIX2) || encrypted.startsWith(ENCRYPT_V1_PREFIX_PROBABLY2)) {
10134
10686
  return await tryDecryption([
10135
10687
  async () => await decrypt3(encrypted, passphrase, false),
10136
10688
  async () => await decrypt3(encrypted, passphrase, true)
@@ -10142,7 +10694,12 @@ async function decryptString(encrypted, passphrase) {
10142
10694
  }
10143
10695
 
10144
10696
  // lib/livesync-commonlib/src/services/base/SettingService.ts
10145
- import { encryptWithEphemeralSalt as encryptWithEphemeralSalt2 } from "octagonal-wheels/encryption/hkdf";
10697
+ import { encryptWithEphemeralSalt as encryptWithEphemeralSalt2, HKDF_SALTED_ENCRYPTED_PREFIX as HKDF_SALTED_ENCRYPTED_PREFIX2 } from "octagonal-wheels/encryption/hkdf";
10698
+ import {
10699
+ ENCRYPT_V1_PREFIX_PROBABLY as ENCRYPT_V1_PREFIX_PROBABLY3,
10700
+ ENCRYPT_V2_PREFIX as ENCRYPT_V2_PREFIX4,
10701
+ ENCRYPT_V3_PREFIX as ENCRYPT_V3_PREFIX3
10702
+ } from "octagonal-wheels/encryption/encryption";
10146
10703
 
10147
10704
  // lib/livesync-commonlib/src/common/ConnectionString.ts
10148
10705
  var PROXY_SCHEME = "https";
@@ -10448,11 +11005,272 @@ function activateP2PRemoteConfiguration(settings, id) {
10448
11005
  }
10449
11006
  }
10450
11007
 
11008
+ // lib/livesync-commonlib/src/common/models/setting.policy.ts
11009
+ var SettingPolicies = {
11010
+ Default: { markdown: "include", persistence: "include" },
11011
+ LocalOnly: { markdown: "omit", persistence: "include" },
11012
+ DeviceLocal: { markdown: "include", persistence: "device" },
11013
+ MarkdownCredentials: { markdown: "credentials", persistence: "include" },
11014
+ RemoteProfiles: { markdown: "credentials", persistence: "profiles" },
11015
+ LocalConnection: { markdown: "include", persistence: "connection" },
11016
+ ConnectionCredentials: { markdown: "credentials", persistence: "connection" },
11017
+ ConnectionContext: { markdown: "include", persistence: "connection-context" },
11018
+ E2EEPassphrase: { markdown: "credentials", persistence: "passphrase" },
11019
+ IdDerivationKey: { markdown: "credentials", persistence: "id-key" },
11020
+ RuntimeOnly: { markdown: "omit", persistence: "omit" }
11021
+ };
11022
+ var SETTINGS_PROPERTY_POLICY = {
11023
+ liveSync: SettingPolicies.Default,
11024
+ batchSaveInLiveSync: SettingPolicies.Default,
11025
+ syncOnSave: SettingPolicies.Default,
11026
+ syncOnStart: SettingPolicies.Default,
11027
+ strictContentCheckOnStartup: SettingPolicies.LocalOnly,
11028
+ syncOnFileOpen: SettingPolicies.Default,
11029
+ syncOnEditorSave: SettingPolicies.Default,
11030
+ keepReplicationActiveInBackground: SettingPolicies.Default,
11031
+ allowSleepDuringSynchronisation: SettingPolicies.Default,
11032
+ allowSleepDuringSynchronisationOnDesktop: SettingPolicies.Default,
11033
+ syncMinimumInterval: SettingPolicies.Default,
11034
+ showVerboseLog: SettingPolicies.Default,
11035
+ lessInformationInLog: SettingPolicies.Default,
11036
+ showLongerLogInsideEditor: SettingPolicies.Default,
11037
+ showStatusOnEditor: SettingPolicies.Default,
11038
+ showStatusOnStatusbar: SettingPolicies.Default,
11039
+ showOnlyIconsOnEditor: SettingPolicies.Default,
11040
+ hideFileWarningNotice: SettingPolicies.Default,
11041
+ networkWarningStyle: SettingPolicies.Default,
11042
+ displayLanguage: SettingPolicies.Default,
11043
+ trashInsteadDelete: SettingPolicies.Default,
11044
+ doNotDeleteFolder: SettingPolicies.Default,
11045
+ batchSave: SettingPolicies.Default,
11046
+ batchSaveMinimumDelay: SettingPolicies.Default,
11047
+ batchSaveMaximumDelay: SettingPolicies.Default,
11048
+ syncMaxSizeInMB: SettingPolicies.Default,
11049
+ useIgnoreFiles: SettingPolicies.Default,
11050
+ ignoreFiles: SettingPolicies.Default,
11051
+ processSizeMismatchedFiles: SettingPolicies.Default,
11052
+ syncOnlyRegEx: SettingPolicies.Default,
11053
+ syncIgnoreRegEx: SettingPolicies.Default,
11054
+ syncAfterMerge: SettingPolicies.Default,
11055
+ resolveConflictsByNewerFile: SettingPolicies.Default,
11056
+ writeDocumentsIfConflicted: SettingPolicies.Default,
11057
+ disableMarkdownAutoMerge: SettingPolicies.Default,
11058
+ configPassphraseStore: SettingPolicies.Default,
11059
+ encryptedPassphrase: SettingPolicies.LocalOnly,
11060
+ encryptedIdDerivationKey: SettingPolicies.LocalOnly,
11061
+ encryptedCouchDBConnection: SettingPolicies.LocalOnly,
11062
+ periodicReplication: SettingPolicies.Default,
11063
+ periodicReplicationInterval: SettingPolicies.Default,
11064
+ syncInternalFiles: SettingPolicies.Default,
11065
+ syncInternalFilesBeforeReplication: SettingPolicies.Default,
11066
+ syncInternalFilesInterval: SettingPolicies.Default,
11067
+ syncInternalFilesIgnorePatterns: SettingPolicies.Default,
11068
+ syncInternalFilesTargetPatterns: SettingPolicies.Default,
11069
+ watchInternalFileChanges: SettingPolicies.Default,
11070
+ suppressNotifyHiddenFilesChange: SettingPolicies.Default,
11071
+ syncInternalFileOverwritePatterns: SettingPolicies.Default,
11072
+ usePluginSync: SettingPolicies.Default,
11073
+ usePluginSettings: SettingPolicies.Default,
11074
+ showOwnPlugins: SettingPolicies.Default,
11075
+ autoSweepPlugins: SettingPolicies.Default,
11076
+ autoSweepPluginsPeriodic: SettingPolicies.Default,
11077
+ notifyPluginOrSettingUpdated: SettingPolicies.Default,
11078
+ deviceAndVaultName: SettingPolicies.DeviceLocal,
11079
+ usePluginSyncV2: SettingPolicies.Default,
11080
+ usePluginEtc: SettingPolicies.Default,
11081
+ pluginSyncExtendedSetting: SettingPolicies.Default,
11082
+ useAdvancedMode: SettingPolicies.Default,
11083
+ usePowerUserMode: SettingPolicies.Default,
11084
+ useEdgeCaseMode: SettingPolicies.Default,
11085
+ notifyThresholdOfRemoteStorageSize: SettingPolicies.Default,
11086
+ disableWorkerForGeneratingChunks: SettingPolicies.Default,
11087
+ processSmallFilesInUIThread: SettingPolicies.Default,
11088
+ savingDelay: SettingPolicies.Default,
11089
+ gcDelay: SettingPolicies.Default,
11090
+ skipOlderFilesOnSync: SettingPolicies.Default,
11091
+ useIndexedDBAdapter: SettingPolicies.Default,
11092
+ enableDebugTools: SettingPolicies.Default,
11093
+ writeLogToTheFile: SettingPolicies.Default,
11094
+ settingSyncFile: SettingPolicies.Default,
11095
+ writeCredentialsForSettingSync: SettingPolicies.Default,
11096
+ notifyAllSettingSyncFile: SettingPolicies.Default,
11097
+ suspendFileWatching: SettingPolicies.Default,
11098
+ suspendParseReplicationResult: SettingPolicies.Default,
11099
+ doNotSuspendOnFetching: SettingPolicies.Default,
11100
+ maxMTimeForReflectEvents: SettingPolicies.Default,
11101
+ versionUpFlash: SettingPolicies.Default,
11102
+ settingVersion: SettingPolicies.Default,
11103
+ isConfigured: SettingPolicies.Default,
11104
+ lastReadUpdates: SettingPolicies.Default,
11105
+ doctorProcessedVersion: SettingPolicies.Default,
11106
+ remoteConfigurations: SettingPolicies.RemoteProfiles,
11107
+ activeConfigurationId: SettingPolicies.MarkdownCredentials,
11108
+ P2P_ActiveRemoteConfigurationId: SettingPolicies.MarkdownCredentials,
11109
+ couchDB_URI: SettingPolicies.LocalConnection,
11110
+ couchDB_USER: SettingPolicies.ConnectionCredentials,
11111
+ couchDB_PASSWORD: SettingPolicies.ConnectionCredentials,
11112
+ couchDB_DBNAME: SettingPolicies.LocalConnection,
11113
+ couchDB_CustomHeaders: SettingPolicies.ConnectionCredentials,
11114
+ useJWT: SettingPolicies.Default,
11115
+ jwtAlgorithm: SettingPolicies.Default,
11116
+ jwtKey: SettingPolicies.ConnectionCredentials,
11117
+ jwtKid: SettingPolicies.ConnectionCredentials,
11118
+ jwtSub: SettingPolicies.ConnectionCredentials,
11119
+ jwtExpDuration: SettingPolicies.Default,
11120
+ useRequestAPI: SettingPolicies.Default,
11121
+ useCouchDBCacheControlHeadersOnly: SettingPolicies.Default,
11122
+ accessKey: SettingPolicies.ConnectionCredentials,
11123
+ secretKey: SettingPolicies.ConnectionCredentials,
11124
+ bucket: SettingPolicies.LocalConnection,
11125
+ region: SettingPolicies.ConnectionContext,
11126
+ endpoint: SettingPolicies.LocalConnection,
11127
+ useCustomRequestHandler: SettingPolicies.Default,
11128
+ bucketCustomHeaders: SettingPolicies.ConnectionCredentials,
11129
+ bucketPrefix: SettingPolicies.Default,
11130
+ forcePathStyle: SettingPolicies.Default,
11131
+ remoteType: SettingPolicies.Default,
11132
+ encrypt: SettingPolicies.Default,
11133
+ acceptUnencryptedContent: SettingPolicies.Default,
11134
+ passphrase: SettingPolicies.E2EEPassphrase,
11135
+ idDerivationVersion: SettingPolicies.MarkdownCredentials,
11136
+ pathNormalizationVersion: SettingPolicies.MarkdownCredentials,
11137
+ idDerivationKey: SettingPolicies.IdDerivationKey,
11138
+ usePathObfuscation: SettingPolicies.Default,
11139
+ encryptInternalMetadata: SettingPolicies.Default,
11140
+ E2EEAlgorithm: SettingPolicies.Default,
11141
+ hashAlg: SettingPolicies.Default,
11142
+ minimumChunkSize: SettingPolicies.Default,
11143
+ customChunkSize: SettingPolicies.Default,
11144
+ longLineThreshold: SettingPolicies.Default,
11145
+ useSegmenter: SettingPolicies.Default,
11146
+ enableChunkSplitterV2: SettingPolicies.Default,
11147
+ doNotUseFixedRevisionForChunks: SettingPolicies.Default,
11148
+ chunkSplitterVersion: SettingPolicies.Default,
11149
+ useEden: SettingPolicies.Default,
11150
+ maxChunksInEden: SettingPolicies.Default,
11151
+ maxTotalLengthInEden: SettingPolicies.Default,
11152
+ maxAgeInEden: SettingPolicies.Default,
11153
+ tweakModified: SettingPolicies.Default,
11154
+ checkIntegrityOnSave: SettingPolicies.Default,
11155
+ useHistory: SettingPolicies.Default,
11156
+ disableRequestURI: SettingPolicies.Default,
11157
+ sendChunksBulk: SettingPolicies.Default,
11158
+ sendChunksBulkMaxSize: SettingPolicies.Default,
11159
+ useDynamicIterationCount: SettingPolicies.Default,
11160
+ doNotPaceReplication: SettingPolicies.Default,
11161
+ readChunksOnline: SettingPolicies.Default,
11162
+ useOnlyLocalChunk: SettingPolicies.Default,
11163
+ concurrencyOfReadChunksOnline: SettingPolicies.Default,
11164
+ minimumIntervalOfReadChunksOnline: SettingPolicies.Default,
11165
+ enableCompression: SettingPolicies.Default,
11166
+ batch_size: SettingPolicies.Default,
11167
+ batches_limit: SettingPolicies.Default,
11168
+ ignoreVersionCheck: SettingPolicies.Default,
11169
+ disableCheckingConfigMismatch: SettingPolicies.Default,
11170
+ autoAcceptCompatibleTweak: SettingPolicies.Default,
11171
+ hashCacheMaxCount: SettingPolicies.Default,
11172
+ hashCacheMaxAmount: SettingPolicies.Default,
11173
+ permitEmptyPassphrase: SettingPolicies.Default,
11174
+ handleFilenameCaseSensitive: SettingPolicies.Default,
11175
+ checkConflictOnlyOnOpen: SettingPolicies.Default,
11176
+ showMergeDialogOnlyOnActive: SettingPolicies.Default,
11177
+ additionalSuffixOfDatabaseName: SettingPolicies.LocalOnly,
11178
+ useTimeouts: SettingPolicies.Default,
11179
+ deleteMetadataOfDeletedFiles: SettingPolicies.Default,
11180
+ automaticallyDeleteMetadataOfDeletedFiles: SettingPolicies.Default,
11181
+ P2P_AutoAccepting: SettingPolicies.Default,
11182
+ P2P_AutoSyncPeers: SettingPolicies.Default,
11183
+ P2P_AutoWatchPeers: SettingPolicies.Default,
11184
+ P2P_SyncOnReplication: SettingPolicies.Default,
11185
+ P2P_RebuildFrom: SettingPolicies.Default,
11186
+ P2P_AutoAcceptingPeers: SettingPolicies.Default,
11187
+ P2P_AutoDenyingPeers: SettingPolicies.Default,
11188
+ P2P_IsHeadless: SettingPolicies.Default,
11189
+ P2P_iceServers: SettingPolicies.RuntimeOnly,
11190
+ P2P_iceServersExpiresAt: SettingPolicies.RuntimeOnly,
11191
+ P2P_Enabled: SettingPolicies.Default,
11192
+ P2P_relays: SettingPolicies.Default,
11193
+ P2P_roomID: SettingPolicies.Default,
11194
+ P2P_passphrase: SettingPolicies.MarkdownCredentials,
11195
+ P2P_AppID: SettingPolicies.Default,
11196
+ P2P_AutoStart: SettingPolicies.Default,
11197
+ P2P_AutoBroadcast: SettingPolicies.Default,
11198
+ P2P_DevicePeerName: SettingPolicies.DeviceLocal,
11199
+ P2P_turnServers: SettingPolicies.Default,
11200
+ P2P_turnUsername: SettingPolicies.MarkdownCredentials,
11201
+ P2P_turnCredential: SettingPolicies.MarkdownCredentials,
11202
+ P2P_managedType: SettingPolicies.RuntimeOnly,
11203
+ P2P_managedId: SettingPolicies.RuntimeOnly,
11204
+ P2P_managedToken: SettingPolicies.RuntimeOnly,
11205
+ P2P_maxWirePayloadBytes: SettingPolicies.Default,
11206
+ P2P_connectionPath: SettingPolicies.Default,
11207
+ P2P_useDiagRTC: SettingPolicies.Default
11208
+ };
11209
+ var settingKeys = Object.keys(SETTINGS_PROPERTY_POLICY);
11210
+ var protectedConnectionKeys = settingKeys.filter(
11211
+ (key) => SETTINGS_PROPERTY_POLICY[key].persistence === "connection"
11212
+ );
11213
+ var connectionKeys = settingKeys.filter(
11214
+ (key) => SETTINGS_PROPERTY_POLICY[key].persistence === "connection" || SETTINGS_PROPERTY_POLICY[key].persistence === "connection-context"
11215
+ );
11216
+ var omittedPersistenceKeys = settingKeys.filter((key) => SETTINGS_PROPERTY_POLICY[key].persistence === "omit");
11217
+ function selectConnectionSettings(settings) {
11218
+ const connection = {};
11219
+ for (const key of connectionKeys) connection[key] = settings[key];
11220
+ return connection;
11221
+ }
11222
+ function hasConnectionSettings(settings) {
11223
+ return protectedConnectionKeys.some((key) => settings[key] !== "");
11224
+ }
11225
+ function clearConnectionSettings(settings) {
11226
+ for (const key of connectionKeys) settings[key] = "";
11227
+ }
11228
+ function restoreConnectionSettings(settings, payload) {
11229
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
11230
+ const connection = payload;
11231
+ if (connectionKeys.some((key) => key in connection && typeof connection[key] !== "string")) return false;
11232
+ for (const key of connectionKeys) {
11233
+ if (key in connection) settings[key] = connection[key];
11234
+ }
11235
+ return true;
11236
+ }
11237
+ function omitUnpersistedSettings(settings) {
11238
+ for (const key of omittedPersistenceKeys) delete settings[key];
11239
+ }
11240
+ function requireConfigurationCiphertext(value) {
11241
+ if (value === "") throw new Error("Failed to encrypt configuration. Settings were not saved.");
11242
+ return value;
11243
+ }
11244
+ function prepareSettingsForPersistence(settings) {
11245
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(settings.acceptUnencryptedContent);
11246
+ if (hasConnectionSettings(settings)) throw new Error("Connection settings were not prepared for persistence.");
11247
+ if (settings.encrypt && settings.passphrase !== "")
11248
+ throw new Error("The passphrase was not prepared for persistence.");
11249
+ if (settings.idDerivationVersion === 1 && settings.idDerivationKey !== "") {
11250
+ throw new Error("The ID derivation key was not prepared for persistence.");
11251
+ }
11252
+ if (omittedPersistenceKeys.some((key) => key in settings)) {
11253
+ throw new Error("Runtime settings were not removed before persistence.");
11254
+ }
11255
+ if (settings.configPassphraseStore !== "" && Object.values(settings.remoteConfigurations).some(
11256
+ (profile) => profile.uri.trim() !== "" && !profile.isEncrypted
11257
+ )) {
11258
+ throw new Error("Remote configurations were not prepared for persistence.");
11259
+ }
11260
+ return settings;
11261
+ }
11262
+
10451
11263
  // lib/livesync-commonlib/src/services/base/SettingService.ts
11264
+ var ConfigurationPassphraseError = class extends Error {
11265
+ };
10452
11266
  var SettingService = class extends ServiceBase {
10453
11267
  deviceAndVaultName = "";
10454
11268
  APIService;
10455
11269
  onDisplayLanguageChanged;
11270
+ /** Exact-key device values, including legacy keys outside the Vault namespace. */
11271
+ deviceValues;
11272
+ /** Device values scoped by the current Vault name and database suffix. */
11273
+ config;
10456
11274
  _settings;
10457
11275
  get settings() {
10458
11276
  return this._settings;
@@ -10462,6 +11280,7 @@ var SettingService = class extends ServiceBase {
10462
11280
  }
10463
11281
  _lastPersistedSettings;
10464
11282
  _settingsMigrationState;
11283
+ saveQueue = Promise.resolve();
10465
11284
  getSettingsMigrationState() {
10466
11285
  return this._settingsMigrationState;
10467
11286
  }
@@ -10469,6 +11288,12 @@ var SettingService = class extends ServiceBase {
10469
11288
  constructor(context, dependencies) {
10470
11289
  super(context);
10471
11290
  this.APIService = dependencies.APIService;
11291
+ this.deviceValues = dependencies.deviceValues;
11292
+ this.config = createDeletableValueStore({
11293
+ get: (key) => this.deviceValues.getValue(this.getKey(key)),
11294
+ set: (key, value) => this.deviceValues.setValue(this.getKey(key), value),
11295
+ delete: (key) => this.deviceValues.delete(this.getKey(key))
11296
+ });
10472
11297
  this.onDisplayLanguageChanged = dependencies.onDisplayLanguageChanged;
10473
11298
  this._log = createInstanceLogFunction("SettingService", this.APIService);
10474
11299
  }
@@ -10477,6 +11302,7 @@ var SettingService = class extends ServiceBase {
10477
11302
  * @param settings The settings to adjust.
10478
11303
  */
10479
11304
  adjustSettings(settings) {
11305
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(settings.acceptUnencryptedContent);
10480
11306
  if (migrateLegacyRemoteConfigurationsInPlace(settings, (message) => {
10481
11307
  this._log(message, LOG_LEVEL_NOTICE);
10482
11308
  })) {
@@ -10521,26 +11347,9 @@ var SettingService = class extends ServiceBase {
10521
11347
  /**
10522
11348
  * Save the current device and vault name to settings, aside from the main settings.
10523
11349
  */
10524
- saveDeviceAndVaultName() {
11350
+ async saveDeviceAndVaultName() {
10525
11351
  const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.APIService.getSystemVaultName() + this.additionalSuffixOfDatabaseName();
10526
- this.setDeviceLocalConfig(lsKey, this.deviceAndVaultName);
10527
- }
10528
- /**
10529
- * Read an exact key from the host's device-local configuration store.
10530
- *
10531
- * Unlike the main settings document, this state is not synchronised. Callers
10532
- * which need Vault namespacing should normally use {@link getSmallConfig}.
10533
- */
10534
- getDeviceLocalConfig(key) {
10535
- return this.getItem(key);
10536
- }
10537
- /** Store an exact key in the host's non-synchronised configuration store. */
10538
- setDeviceLocalConfig(key, value) {
10539
- this.setItem(key, value);
10540
- }
10541
- /** Delete an exact key from the host's non-synchronised configuration store. */
10542
- deleteDeviceLocalConfig(key) {
10543
- this.deleteItem(key);
11352
+ await this.deviceValues.setValue(lsKey, this.deviceAndVaultName);
10544
11353
  }
10545
11354
  additionalSuffixOfDatabaseName() {
10546
11355
  const suffix = this.settings?.additionalSuffixOfDatabaseName;
@@ -10555,46 +11364,134 @@ var SettingService = class extends ServiceBase {
10555
11364
  const addSuffix = this.additionalSuffixOfDatabaseName();
10556
11365
  return `${keyMain}${addSuffix}-${key}`;
10557
11366
  }
10558
- setSmallConfig(key, value) {
10559
- const dbKey = this.getKey(key);
10560
- this.setDeviceLocalConfig(dbKey, value);
10561
- }
10562
- getSmallConfig(key) {
10563
- const dbKey = this.getKey(key);
10564
- return this.getDeviceLocalConfig(dbKey) ?? "";
10565
- }
10566
- deleteSmallConfig(key) {
10567
- const dbKey = this.getKey(key);
10568
- this.deleteDeviceLocalConfig(dbKey);
10569
- }
10570
11367
  /**
10571
11368
  * Save the current settings to storage.
10572
11369
  */
10573
- async saveSettingData() {
10574
- this.saveDeviceAndVaultName();
11370
+ saveSettingData() {
11371
+ return this.serialiseSave(async () => {
11372
+ const prepared = await this.prepareSettingSave(this.cloneSettings(this.settings));
11373
+ await this.writePreparedSettings(prepared);
11374
+ this.commitPreparedSettings(prepared);
11375
+ });
11376
+ }
11377
+ serialiseSave(operation) {
11378
+ const result = this.saveQueue.then(operation);
11379
+ this.saveQueue = result.catch(() => void 0);
11380
+ return result;
11381
+ }
11382
+ /** Change the configuration wrapper without changing the protected plaintext values. */
11383
+ changeConfigurationEncryption(store, passphrase) {
11384
+ const result = this.serialiseSave(async () => {
11385
+ if (store !== "" && store !== "LOCALSTORAGE" && store !== "ASK_AT_LAUNCH") {
11386
+ throw new Error("The configuration passphrase storage mode is unsupported.");
11387
+ }
11388
+ const oldLocalKey = await this.deviceValues.getValue("ls-setting-passphrase");
11389
+ const settings = this.cloneSettings(this.settings);
11390
+ let targetKey;
11391
+ if (store === "LOCALSTORAGE") {
11392
+ targetKey = passphrase ?? oldLocalKey ?? false;
11393
+ } else if (store === "") {
11394
+ targetKey = "*";
11395
+ } else {
11396
+ targetKey = await this.getSavingPassphrase({ ...settings, configPassphraseStore: store });
11397
+ }
11398
+ if (!targetKey) {
11399
+ throw new Error("A configuration passphrase is required. Settings were not saved.");
11400
+ }
11401
+ await this.prepareConfigurationKeyChange(settings, targetKey);
11402
+ settings.configPassphraseStore = store;
11403
+ const prepared = await this.prepareSettingSave(settings, targetKey);
11404
+ const changesLocalKey = store === "LOCALSTORAGE" && targetKey !== oldLocalKey;
11405
+ try {
11406
+ if (changesLocalKey) await this.deviceValues.setValue("ls-setting-passphrase", targetKey);
11407
+ await this.writePreparedSettings(prepared);
11408
+ } catch (error) {
11409
+ if (changesLocalKey) await this.restoreConfigurationPassphrase(oldLocalKey, error);
11410
+ throw error;
11411
+ }
11412
+ this.settings.configPassphraseStore = store;
11413
+ this.commitPreparedSettings(prepared);
11414
+ });
11415
+ return result.catch((error) => {
11416
+ this._log(this.context.translate("SettingService.ConfigurationEncryptionSaveFailed"), LOG_LEVEL_URGENT);
11417
+ throw error;
11418
+ });
11419
+ }
11420
+ async restoreConfigurationPassphrase(previous, cause) {
11421
+ try {
11422
+ if (previous) await this.deviceValues.setValue("ls-setting-passphrase", previous);
11423
+ else await this.deviceValues.delete("ls-setting-passphrase");
11424
+ } catch {
11425
+ const message = this.context.translate("SettingService.ConfigurationPassphraseRollbackFailed");
11426
+ this._log(message, LOG_LEVEL_URGENT);
11427
+ throw new Error(message, { cause });
11428
+ }
11429
+ }
11430
+ async prepareConfigurationKeyChange(settings, targetKey) {
11431
+ for (const config of Object.values(settings.remoteConfigurations)) {
11432
+ if (config.isEncrypted && this.isPlainConfigurationUri(config.uri)) config.isEncrypted = false;
11433
+ }
11434
+ const hasCiphertext = this.hasProtectedConfiguration(settings);
11435
+ if (!hasCiphertext) return;
11436
+ const oldKey = await this.getSavingPassphrase(settings);
11437
+ const failure = () => new Error(this.context.translate("SettingService.ConfigurationCouldNotBeDecrypted"));
11438
+ if (!oldKey) throw failure();
11439
+ if (settings.encryptedCouchDBConnection) {
11440
+ const connection = this.tryDecodeJson(
11441
+ await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, oldKey)
11442
+ );
11443
+ if (!restoreConnectionSettings(this.cloneSettings(settings), connection)) throw failure();
11444
+ settings.encryptedCouchDBConnection = "";
11445
+ }
11446
+ if (settings.encryptedPassphrase) {
11447
+ const plaintext = await this.decryptConfigurationItem(settings.encryptedPassphrase, oldKey);
11448
+ if (plaintext === false) throw failure();
11449
+ settings.encryptedPassphrase = requireConfigurationCiphertext(
11450
+ await this.encryptPlainConfigurationItem(plaintext, settings, targetKey)
11451
+ );
11452
+ }
11453
+ if (settings.idDerivationVersion === 1 && settings.encryptedIdDerivationKey) {
11454
+ const idKey = await this.decryptConfigurationItem(settings.encryptedIdDerivationKey, oldKey);
11455
+ if (idKey === false) throw failure();
11456
+ configuredIdKey({ ...settings, idDerivationKey: idKey });
11457
+ }
11458
+ for (const config of Object.values(settings.remoteConfigurations)) {
11459
+ if (!config.isEncrypted) continue;
11460
+ const plaintext = await this.decryptConfigurationItem(config.uri, oldKey);
11461
+ if (plaintext === false) {
11462
+ try {
11463
+ ConnectionStringParser.parse(config.uri);
11464
+ } catch {
11465
+ throw failure();
11466
+ }
11467
+ } else {
11468
+ config.uri = plaintext;
11469
+ }
11470
+ config.isEncrypted = false;
11471
+ }
11472
+ }
11473
+ async prepareSettingSave(settings, selectedPassphrase) {
10575
11474
  const previousSettings = this._lastPersistedSettings ?? this.cloneSettings(this.settings);
10576
- const settings = this.cloneSettings(this.settings);
10577
11475
  const hookResults = await this.onBeforeSaveSettingData(settings, previousSettings);
11476
+ const savedPatch = {};
10578
11477
  for (const patch of hookResults) {
10579
11478
  if (patch instanceof Error || !patch) continue;
10580
11479
  Object.assign(settings, patch);
10581
- Object.assign(this.settings, patch);
11480
+ Object.assign(savedPatch, patch);
10582
11481
  }
11482
+ const runtime = this.cloneSettings(settings);
10583
11483
  const idKey = configuredIdKey(settings);
11484
+ const configurationPassphrase = selectedPassphrase ?? await this.getSavingPassphrase(settings);
10584
11485
  if (settings.idDerivationVersion === 1) {
10585
11486
  if (idKey === false) {
10586
11487
  throw new Error("The configured ID derivation key is unavailable.");
10587
11488
  }
10588
- let passphrase = this.usedPassphrase;
10589
- if (passphrase === "") {
10590
- passphrase = await this.getPassphrase(settings);
10591
- }
10592
- if (passphrase === false || passphrase === "") {
11489
+ if (!configurationPassphrase) {
10593
11490
  const message = "Failed to retrieve a passphrase for the ID derivation key. Settings were not saved.";
10594
11491
  this._log(message, LOG_LEVEL_URGENT);
10595
11492
  throw new Error(message);
10596
11493
  }
10597
- const encryptedIdKey = await encryptString(idKey, passphrase + SALT_OF_PASSPHRASE);
11494
+ const encryptedIdKey = await encryptString(idKey, configurationPassphrase + SALT_OF_PASSPHRASE);
10598
11495
  if (encryptedIdKey === "") {
10599
11496
  const message = "Failed to encrypt the ID derivation key. Settings were not saved.";
10600
11497
  this._log(message, LOG_LEVEL_URGENT);
@@ -10602,76 +11499,74 @@ var SettingService = class extends ServiceBase {
10602
11499
  }
10603
11500
  settings.encryptedIdDerivationKey = encryptedIdKey;
10604
11501
  settings.idDerivationKey = "";
10605
- this.usedPassphrase = passphrase;
10606
11502
  } else {
10607
11503
  settings.encryptedIdDerivationKey = "";
10608
11504
  }
10609
11505
  settings.deviceAndVaultName = "";
10610
11506
  if (settings.P2P_DevicePeerName && settings.P2P_DevicePeerName.trim() !== "") {
10611
- this._log("Saving device peer name to small config");
10612
- this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME, settings.P2P_DevicePeerName.trim());
10613
11507
  settings.P2P_DevicePeerName = "";
10614
11508
  }
10615
- delete settings.P2P_managedType;
10616
- delete settings.P2P_managedId;
10617
- delete settings.P2P_managedToken;
10618
- if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) {
11509
+ omitUnpersistedSettings(settings);
11510
+ if (!configurationPassphrase) {
10619
11511
  if (Object.values(settings.remoteConfigurations).some((config) => this.hasManagedP2PProfileURI(config.uri))) {
10620
11512
  const message = "Failed to retrieve a passphrase for managed P2P source data. Settings were not saved.";
10621
11513
  this._log(message, LOG_LEVEL_URGENT);
10622
11514
  throw new Error(message);
10623
11515
  }
11516
+ if (hasConnectionSettings(settings) || settings.encrypt && settings.passphrase !== "" || settings.configPassphraseStore !== "" && Object.values(settings.remoteConfigurations).some(
11517
+ (config) => !config.isEncrypted && config.uri.trim() !== ""
11518
+ )) {
11519
+ const message = "Failed to retrieve a configuration passphrase. Settings were not saved.";
11520
+ this._log(message, LOG_LEVEL_URGENT);
11521
+ throw new Error(message);
11522
+ }
10624
11523
  this._log("Failed to retrieve passphrase. data.json contains unencrypted items!", LOG_LEVEL_NOTICE);
10625
11524
  } else {
10626
- if (settings.couchDB_PASSWORD != "" || settings.couchDB_URI != "" || settings.couchDB_USER != "" || settings.couchDB_DBNAME) {
10627
- const connectionSetting = {
10628
- couchDB_DBNAME: settings.couchDB_DBNAME,
10629
- couchDB_PASSWORD: settings.couchDB_PASSWORD,
10630
- couchDB_URI: settings.couchDB_URI,
10631
- couchDB_USER: settings.couchDB_USER,
10632
- accessKey: settings.accessKey,
10633
- bucket: settings.bucket,
10634
- endpoint: settings.endpoint,
10635
- region: settings.region,
10636
- secretKey: settings.secretKey,
10637
- useCustomRequestHandler: settings.useCustomRequestHandler,
10638
- bucketCustomHeaders: settings.bucketCustomHeaders,
10639
- couchDB_CustomHeaders: settings.couchDB_CustomHeaders,
10640
- useJWT: settings.useJWT,
10641
- jwtKey: settings.jwtKey,
10642
- jwtAlgorithm: settings.jwtAlgorithm,
10643
- jwtKid: settings.jwtKid,
10644
- jwtExpDuration: settings.jwtExpDuration,
10645
- jwtSub: settings.jwtSub,
10646
- useRequestAPI: settings.useRequestAPI,
10647
- bucketPrefix: settings.bucketPrefix,
10648
- forcePathStyle: settings.forcePathStyle
10649
- };
10650
- settings.encryptedCouchDBConnection = await this.encryptConfigurationItem(
10651
- JSON.stringify(connectionSetting),
10652
- settings
11525
+ if (hasConnectionSettings(settings)) {
11526
+ settings.encryptedCouchDBConnection = requireConfigurationCiphertext(
11527
+ await this.encryptConfigurationItem(
11528
+ JSON.stringify(selectConnectionSettings(settings)),
11529
+ settings,
11530
+ configurationPassphrase
11531
+ )
11532
+ );
11533
+ clearConnectionSettings(settings);
11534
+ } else if (settings.encryptedCouchDBConnection) {
11535
+ const existingConnection = this.tryDecodeJson(
11536
+ await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, configurationPassphrase)
10653
11537
  );
10654
- settings.couchDB_PASSWORD = "";
10655
- settings.couchDB_DBNAME = "";
10656
- settings.couchDB_URI = "";
10657
- settings.couchDB_USER = "";
10658
- settings.accessKey = "";
10659
- settings.bucket = "";
10660
- settings.region = "";
10661
- settings.secretKey = "";
10662
- settings.endpoint = "";
11538
+ if (restoreConnectionSettings(this.cloneSettings(settings), existingConnection)) {
11539
+ settings.encryptedCouchDBConnection = "";
11540
+ }
10663
11541
  }
10664
11542
  if (settings.encrypt && settings.passphrase != "") {
10665
- settings.encryptedPassphrase = await this.encryptPlainConfigurationItem(settings.passphrase, settings);
11543
+ settings.encryptedPassphrase = requireConfigurationCiphertext(
11544
+ await this.encryptPlainConfigurationItem(settings.passphrase, settings, configurationPassphrase)
11545
+ );
10666
11546
  settings.passphrase = "";
10667
11547
  }
10668
- await this.encryptRemoteConfigurationUris(settings);
11548
+ await this.encryptRemoteConfigurationUris(settings, configurationPassphrase);
10669
11549
  }
10670
- await this.saveData(settings);
10671
- this._lastPersistedSettings = this.cloneSettings(this.settings);
10672
- void this.onSettingSaved(settings);
11550
+ const persisted = prepareSettingsForPersistence(settings);
11551
+ return { persisted, runtime, patch: savedPatch, passphrase: configurationPassphrase };
10673
11552
  }
10674
- async encryptRemoteConfigurationUris(settings) {
11553
+ async writePreparedSettings(prepared) {
11554
+ await this.saveDeviceAndVaultName();
11555
+ if (prepared.runtime.P2P_DevicePeerName?.trim()) {
11556
+ await this.config.setValue(SETTING_KEY_P2P_DEVICE_NAME, prepared.runtime.P2P_DevicePeerName.trim());
11557
+ }
11558
+ await this.saveData(prepared.persisted);
11559
+ }
11560
+ commitPreparedSettings(prepared) {
11561
+ Object.assign(this.settings, prepared.patch);
11562
+ this.settings.encryptedCouchDBConnection = prepared.persisted.encryptedCouchDBConnection;
11563
+ this.settings.encryptedPassphrase = prepared.persisted.encryptedPassphrase;
11564
+ this.settings.encryptedIdDerivationKey = prepared.persisted.encryptedIdDerivationKey;
11565
+ this._lastPersistedSettings = prepared.runtime;
11566
+ if (prepared.passphrase) this.rememberPassphrase(prepared.runtime, prepared.passphrase);
11567
+ void this.onSettingSaved(prepared.persisted);
11568
+ }
11569
+ async encryptRemoteConfigurationUris(settings, passphrase) {
10675
11570
  const configs = settings.remoteConfigurations || {};
10676
11571
  for (const [id, config] of Object.entries(configs)) {
10677
11572
  if (config.isEncrypted || config.uri.trim() === "") {
@@ -10680,7 +11575,7 @@ var SettingService = class extends ServiceBase {
10680
11575
  const managedP2PProfile = this.hasManagedP2PProfileURI(config.uri);
10681
11576
  let encryptedURI;
10682
11577
  try {
10683
- encryptedURI = await this.encryptConfigurationItem(config.uri, settings);
11578
+ encryptedURI = await this.encryptConfigurationItem(config.uri, settings, passphrase);
10684
11579
  } catch (error) {
10685
11580
  if (managedP2PProfile) {
10686
11581
  const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
@@ -10695,6 +11590,11 @@ var SettingService = class extends ServiceBase {
10695
11590
  this._log(message, LOG_LEVEL_URGENT);
10696
11591
  throw new Error(message);
10697
11592
  }
11593
+ if (settings.configPassphraseStore !== "") {
11594
+ const message = `Failed to encrypt remote configuration '${id}'. Settings were not saved.`;
11595
+ this._log(message, LOG_LEVEL_URGENT);
11596
+ throw new Error(message);
11597
+ }
10698
11598
  this._log(
10699
11599
  `Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`,
10700
11600
  LOG_LEVEL_URGENT
@@ -10717,6 +11617,7 @@ var SettingService = class extends ServiceBase {
10717
11617
  return (new URLSearchParams(query).get("managedType") ?? "").trim().length > 0;
10718
11618
  }
10719
11619
  async decryptRemoteConfigurationUris(settings, passphrase) {
11620
+ let verified = false;
10720
11621
  const configs = settings.remoteConfigurations || {};
10721
11622
  for (const [id, config] of Object.entries(configs)) {
10722
11623
  if (!config.isEncrypted) {
@@ -10748,7 +11649,9 @@ var SettingService = class extends ServiceBase {
10748
11649
  uri: decryptedURI,
10749
11650
  isEncrypted: false
10750
11651
  };
11652
+ verified = true;
10751
11653
  }
11654
+ return verified;
10752
11655
  }
10753
11656
  /**
10754
11657
  * Event triggered before realising the settings.
@@ -10832,25 +11735,38 @@ var SettingService = class extends ServiceBase {
10832
11735
  getPassphrase(settings) {
10833
11736
  const methods = {
10834
11737
  "": () => Promise.resolve("*"),
10835
- LOCALSTORAGE: () => Promise.resolve(this.getDeviceLocalConfig("ls-setting-passphrase") ?? false),
10836
- ASK_AT_LAUNCH: () => this.APIService.confirm.askString("Passphrase", "passphrase", "")
11738
+ LOCALSTORAGE: () => this.deviceValues.getValue("ls-setting-passphrase", ""),
11739
+ ASK_AT_LAUNCH: () => this.APIService.confirm.askString(
11740
+ this.context.translate("SettingService.ConfigurationPassphraseTitle"),
11741
+ "passphrase",
11742
+ "",
11743
+ true
11744
+ )
10837
11745
  };
10838
11746
  const method = settings.configPassphraseStore;
10839
11747
  const methodFunc = method in methods ? methods[method] : methods[""];
10840
11748
  return methodFunc();
10841
11749
  }
10842
- usedPassphrase = "";
11750
+ usedPassphrase;
11751
+ getSavingPassphrase(settings) {
11752
+ if (settings.configPassphraseStore === "ASK_AT_LAUNCH" && this.usedPassphrase?.store === "ASK_AT_LAUNCH") {
11753
+ return Promise.resolve(this.usedPassphrase.value);
11754
+ }
11755
+ return this.getPassphrase(settings);
11756
+ }
11757
+ rememberPassphrase(settings, passphrase) {
11758
+ this.usedPassphrase = { store: settings.configPassphraseStore, value: passphrase };
11759
+ }
10843
11760
  /**
10844
11761
  * Clear any used passphrase from memory.
10845
11762
  */
10846
11763
  clearUsedPassphrase() {
10847
- this.usedPassphrase = "";
11764
+ this.usedPassphrase = void 0;
10848
11765
  }
10849
11766
  async decryptConfigurationItem(encrypted, passphrase) {
10850
11767
  try {
10851
11768
  const dec = await decryptString(encrypted, passphrase + SALT_OF_PASSPHRASE);
10852
11769
  if (dec) {
10853
- this.usedPassphrase = passphrase;
10854
11770
  return dec;
10855
11771
  }
10856
11772
  } catch (ex) {
@@ -10859,18 +11775,15 @@ var SettingService = class extends ServiceBase {
10859
11775
  }
10860
11776
  return false;
10861
11777
  }
10862
- async encryptConfigurationItem(src, settings) {
10863
- return this.encryptConfigurationItemWith(src, settings, encryptString);
11778
+ async encryptConfigurationItem(src, settings, passphrase) {
11779
+ return this.encryptConfigurationItemWith(src, settings, encryptString, passphrase);
10864
11780
  }
10865
- async encryptPlainConfigurationItem(src, settings) {
10866
- return this.encryptConfigurationItemWith(src, settings, encryptWithEphemeralSalt2);
11781
+ async encryptPlainConfigurationItem(src, settings, passphrase) {
11782
+ return this.encryptConfigurationItemWith(src, settings, encryptWithEphemeralSalt2, passphrase);
10867
11783
  }
10868
- async encryptConfigurationItemWith(src, settings, encrypt3) {
10869
- if (this.usedPassphrase != "") {
10870
- return await encrypt3(src, this.usedPassphrase + SALT_OF_PASSPHRASE);
10871
- }
10872
- const passphrase = await this.getPassphrase(settings);
10873
- if (passphrase === false) {
11784
+ async encryptConfigurationItemWith(src, settings, encrypt3, selectedPassphrase) {
11785
+ const passphrase = selectedPassphrase ?? await this.getSavingPassphrase(settings);
11786
+ if (!passphrase) {
10874
11787
  this._log(
10875
11788
  "Failed to obtain passphrase when saving data.json! Please verify the configuration.",
10876
11789
  LOG_LEVEL_URGENT
@@ -10879,7 +11792,7 @@ var SettingService = class extends ServiceBase {
10879
11792
  }
10880
11793
  const dec = await encrypt3(src, passphrase + SALT_OF_PASSPHRASE);
10881
11794
  if (dec) {
10882
- this.usedPassphrase = passphrase;
11795
+ if (selectedPassphrase === void 0) this.rememberPassphrase(settings, passphrase);
10883
11796
  return dec;
10884
11797
  }
10885
11798
  return "";
@@ -10889,19 +11802,24 @@ var SettingService = class extends ServiceBase {
10889
11802
  * @param settings The settings to decrypt.
10890
11803
  */
10891
11804
  async decryptSettings(settings) {
10892
- if (settings.idDerivationVersion !== 1) {
10893
- configuredIdKey(settings);
10894
- } else if (!settings.encryptedIdDerivationKey) {
10895
- throw new Error("The configured ID derivation key is missing or unavailable.");
10896
- }
11805
+ this.validateStoredIdConfiguration(settings);
10897
11806
  const passphrase = await this.getPassphrase(settings);
11807
+ const result = await this.decryptSettingsWithPassphrase(settings, passphrase);
11808
+ if (result.verified && passphrase) this.rememberPassphrase(settings, passphrase);
11809
+ return result.settings;
11810
+ }
11811
+ async decryptSettingsWithPassphrase(settings, passphrase) {
11812
+ let verified = false;
11813
+ this.validateStoredIdConfiguration(settings);
10898
11814
  if (settings.idDerivationVersion === 1) {
10899
11815
  if (passphrase === false || passphrase === "") {
10900
- throw new Error("The configured ID derivation key cannot be decrypted without a passphrase.");
11816
+ throw new ConfigurationPassphraseError(
11817
+ "The configured ID derivation key cannot be decrypted without a passphrase."
11818
+ );
10901
11819
  }
10902
11820
  const decryptedIdKey = await this.decryptConfigurationItem(settings.encryptedIdDerivationKey, passphrase);
10903
11821
  if (decryptedIdKey === false) {
10904
- throw new Error("The configured ID derivation key could not be decrypted.");
11822
+ throw new ConfigurationPassphraseError("The configured ID derivation key could not be decrypted.");
10905
11823
  }
10906
11824
  try {
10907
11825
  configuredIdKey({ ...settings, idDerivationKey: decryptedIdKey });
@@ -10909,6 +11827,7 @@ var SettingService = class extends ServiceBase {
10909
11827
  throw new Error("The configured ID derivation key is invalid.");
10910
11828
  }
10911
11829
  settings.idDerivationKey = decryptedIdKey;
11830
+ verified = true;
10912
11831
  }
10913
11832
  if (passphrase === false) {
10914
11833
  this._log("No passphrase found for data.json! Verify configuration before syncing.", LOG_LEVEL_URGENT);
@@ -10923,34 +11842,17 @@ var SettingService = class extends ServiceBase {
10923
11842
  }
10924
11843
  } else {
10925
11844
  if (settings.encryptedCouchDBConnection) {
10926
- const keys = [
10927
- "couchDB_URI",
10928
- "couchDB_USER",
10929
- "couchDB_PASSWORD",
10930
- "couchDB_DBNAME",
10931
- "accessKey",
10932
- "bucket",
10933
- "endpoint",
10934
- "region",
10935
- "secretKey"
10936
- ];
10937
11845
  const decrypted = this.tryDecodeJson(
10938
11846
  await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, passphrase)
10939
11847
  );
10940
- if (decrypted) {
10941
- for (const key of keys) {
10942
- if (key in decrypted) {
10943
- settings[key] = decrypted[key];
10944
- }
10945
- }
10946
- } else {
11848
+ if (!restoreConnectionSettings(settings, decrypted)) {
10947
11849
  this._log(
10948
11850
  "Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",
10949
11851
  LOG_LEVEL_URGENT
10950
11852
  );
10951
- for (const key of keys) {
10952
- settings[key] = "";
10953
- }
11853
+ clearConnectionSettings(settings);
11854
+ } else {
11855
+ verified = true;
10954
11856
  }
10955
11857
  }
10956
11858
  if (settings.encrypt && settings.encryptedPassphrase) {
@@ -10958,6 +11860,7 @@ var SettingService = class extends ServiceBase {
10958
11860
  const decrypted = await this.decryptConfigurationItem(encrypted, passphrase);
10959
11861
  if (decrypted) {
10960
11862
  settings.passphrase = decrypted;
11863
+ verified = true;
10961
11864
  } else {
10962
11865
  this._log(
10963
11866
  "Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",
@@ -10966,9 +11869,80 @@ var SettingService = class extends ServiceBase {
10966
11869
  settings.passphrase = "";
10967
11870
  }
10968
11871
  }
10969
- await this.decryptRemoteConfigurationUris(settings, passphrase);
11872
+ verified = await this.decryptRemoteConfigurationUris(settings, passphrase) || verified;
11873
+ }
11874
+ return { settings, verified };
11875
+ }
11876
+ hasProtectedConfiguration(settings) {
11877
+ return !!(settings.encryptedCouchDBConnection || settings.encrypt && settings.encryptedPassphrase || settings.encryptedIdDerivationKey || Object.values(settings.remoteConfigurations || {}).some(
11878
+ (config) => config.isEncrypted && !this.isPlainConfigurationUri(config.uri)
11879
+ ));
11880
+ }
11881
+ validateStoredIdConfiguration(settings) {
11882
+ if (settings.idDerivationVersion !== 1) {
11883
+ configuredIdKey(settings);
11884
+ } else if (!settings.encryptedIdDerivationKey) {
11885
+ throw new Error("The configured ID derivation key is missing or unavailable.");
11886
+ }
11887
+ }
11888
+ isPlainConfigurationUri(uri) {
11889
+ try {
11890
+ ConnectionStringParser.parse(uri);
11891
+ return true;
11892
+ } catch {
11893
+ return false;
11894
+ }
11895
+ }
11896
+ async loadConfiguration(settings) {
11897
+ if (settings.configPassphraseStore !== "LOCALSTORAGE" || !this.hasProtectedConfiguration(settings)) {
11898
+ return this.decryptSettings(settings);
11899
+ }
11900
+ if (settings.idDerivationVersion === 1) {
11901
+ const ciphertext = settings.encryptedIdDerivationKey;
11902
+ if (![HKDF_SALTED_ENCRYPTED_PREFIX2, ENCRYPT_V1_PREFIX_PROBABLY3, ENCRYPT_V2_PREFIX4, ENCRYPT_V3_PREFIX3].some(
11903
+ (prefix) => ciphertext?.startsWith(prefix)
11904
+ )) {
11905
+ throw new Error("The configured ID derivation key is missing or unavailable.");
11906
+ }
11907
+ } else {
11908
+ configuredIdKey(settings);
11909
+ }
11910
+ const previous = await this.deviceValues.getValue("ls-setting-passphrase");
11911
+ let candidate = previous || false;
11912
+ let retry2 = false;
11913
+ while (true) {
11914
+ if (candidate) {
11915
+ try {
11916
+ const result = await this.decryptSettingsWithPassphrase(this.cloneSettings(settings), candidate);
11917
+ if (result.verified) {
11918
+ if (candidate !== previous) {
11919
+ try {
11920
+ await this.deviceValues.setValue("ls-setting-passphrase", candidate);
11921
+ } catch (error) {
11922
+ await this.restoreConfigurationPassphrase(previous, error);
11923
+ throw error;
11924
+ }
11925
+ }
11926
+ this.rememberPassphrase(settings, candidate);
11927
+ return result.settings;
11928
+ }
11929
+ } catch (error) {
11930
+ if (!(error instanceof ConfigurationPassphraseError)) throw error;
11931
+ }
11932
+ retry2 = true;
11933
+ }
11934
+ candidate = await this.APIService.confirm.askString(
11935
+ this.context.translate(
11936
+ retry2 ? "SettingService.ConfigurationPassphraseRetryTitle" : "SettingService.ConfigurationPassphraseTitle"
11937
+ ),
11938
+ "passphrase",
11939
+ "",
11940
+ true
11941
+ );
11942
+ if (!candidate) {
11943
+ throw new Error(this.context.translate("SettingService.ConfigurationPassphraseCancelled"));
11944
+ }
10970
11945
  }
10971
- return settings;
10972
11946
  }
10973
11947
  async loadSettings() {
10974
11948
  const prepared = prepareSettingsForLoad(await this.loadData());
@@ -10984,7 +11958,7 @@ var SettingService = class extends ServiceBase {
10984
11958
  settings.isConfigured = false;
10985
11959
  }
10986
11960
  }
10987
- this.settings = await this.decryptSettings(settings);
11961
+ this.settings = await this.loadConfiguration(settings);
10988
11962
  this.onDisplayLanguageChanged?.(this.settings.displayLanguage);
10989
11963
  await this.adjustSettings(this.settings);
10990
11964
  const migratedLegacyRemoteConfigurations = !hadRemoteConfigurations && Object.keys(this.settings.remoteConfigurations ?? {}).length > 0;
@@ -11021,9 +11995,9 @@ var SettingService = class extends ServiceBase {
11021
11995
  }
11022
11996
  const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.APIService.getSystemVaultName() + this.additionalSuffixOfDatabaseName();
11023
11997
  if (this.settings.deviceAndVaultName != "") {
11024
- if (!this.getDeviceLocalConfig(lsKey)) {
11998
+ if (!await this.deviceValues.getValue(lsKey)) {
11025
11999
  this.setDeviceAndVaultName(this.settings.deviceAndVaultName);
11026
- this.saveDeviceAndVaultName();
12000
+ await this.saveDeviceAndVaultName();
11027
12001
  this.settings.deviceAndVaultName = "";
11028
12002
  }
11029
12003
  }
@@ -11034,7 +12008,7 @@ var SettingService = class extends ServiceBase {
11034
12008
  );
11035
12009
  this.settings.customChunkSize = 0;
11036
12010
  }
11037
- this.setDeviceAndVaultName(this.getDeviceLocalConfig(lsKey) || "");
12011
+ this.setDeviceAndVaultName(await this.deviceValues.getValue(lsKey) || "");
11038
12012
  if (this.getDeviceAndVaultName() == "") {
11039
12013
  if (this.settings.usePluginSync) {
11040
12014
  this._log("Device name missing. Disabling plug-in sync.", LOG_LEVEL_NOTICE);
@@ -11080,16 +12054,6 @@ var InjectableSettingService = class extends SettingService {
11080
12054
  return Promise.resolve(true);
11081
12055
  });
11082
12056
  }
11083
- setItem(key, value) {
11084
- return compatGlobal.localStorage.setItem(key, value);
11085
- }
11086
- getItem(key) {
11087
- return compatGlobal.localStorage.getItem(key) ?? "";
11088
- }
11089
- deleteItem(key) {
11090
- compatGlobal.localStorage.removeItem(key);
11091
- }
11092
- // override currentSettings = handlers<SettingService<T>>().binder("currentSettings");
11093
12057
  saveData = handlers().binder("saveData");
11094
12058
  loadData = handlers().binder("loadData");
11095
12059
  };
@@ -11504,6 +12468,7 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11504
12468
  const fileProcessing = new InjectableFileProcessingService(context);
11505
12469
  const setting = new InjectableSettingService(context, {
11506
12470
  APIService: API,
12471
+ deviceValues: overrideServiceConstructor.deviceValues,
11507
12472
  onDisplayLanguageChanged: overrideServiceConstructor.onDisplayLanguageChanged
11508
12473
  });
11509
12474
  const appLifecycle = new HeadlessAppLifecycleService(context, {
@@ -11533,10 +12498,7 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11533
12498
  vault,
11534
12499
  setting
11535
12500
  });
11536
- const config = new ConfigServiceBrowserCompat(context, {
11537
- settingService: setting,
11538
- APIService: API
11539
- });
12501
+ const config = setting.config;
11540
12502
  const replicator = new InjectableReplicatorService(context, {
11541
12503
  settingService: setting,
11542
12504
  appLifecycleService: appLifecycle,
@@ -11593,11 +12555,260 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11593
12555
  }
11594
12556
  };
11595
12557
 
11596
- // lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
12558
+ // lib/livesync-commonlib/src/API/DirectFileWatchOwner.ts
12559
+ import { LEVEL_INFO as LEVEL_INFO2, LEVEL_VERBOSE, Logger as Logger19 } from "octagonal-wheels/common/logger";
12560
+ import { bindContext } from "octagonal-wheels/context";
12561
+ import { withScope } from "octagonal-wheels/resource/scope";
11597
12562
  function isNoteEntry(doc) {
11598
- if (!doc) return false;
11599
- return doc.type == "newnote" || doc.type == "plain";
12563
+ return !!doc && (doc.type == "newnote" || doc.type == "plain");
12564
+ }
12565
+ function isActive(session) {
12566
+ return session.owner.session === session;
12567
+ }
12568
+ function isCurrent({ session, item, epoch }) {
12569
+ return isActive(session) && session.connected && session.connection === epoch && session.pending.get(item.id) === item;
12570
+ }
12571
+ function retryDelay(failures) {
12572
+ return Math.min(3e4, 1e3 * 2 ** Math.min(failures - 1, 5));
12573
+ }
12574
+ function documentPath(doc) {
12575
+ return doc && "path" in doc ? doc.path : void 0;
12576
+ }
12577
+ function safePosition(session) {
12578
+ return session.pending.values().next().value?.before ?? session.latest;
12579
+ }
12580
+ function cancelRetry(session) {
12581
+ if (session.retryTimer !== void 0) clearTimeout(session.retryTimer);
12582
+ session.retryTimer = void 0;
12583
+ }
12584
+ function cancelFeed(session) {
12585
+ const state = session.owner.host.state;
12586
+ const changes = state.changes;
12587
+ state.changes = void 0;
12588
+ changes?.cancel();
12589
+ }
12590
+ function stop(session) {
12591
+ session.owner.host.state.watching = false;
12592
+ session.connected = false;
12593
+ session.connection++;
12594
+ cancelRetry(session);
12595
+ if (session.reconnectTimer !== void 0) clearTimeout(session.reconnectTimer);
12596
+ session.reconnectTimer = void 0;
12597
+ session.pending.clear();
12598
+ session.owner.session = void 0;
12599
+ cancelFeed(session);
12600
+ }
12601
+ function schedule(session) {
12602
+ cancelRetry(session);
12603
+ if (!isActive(session) || !session.connected) return;
12604
+ let next = Infinity;
12605
+ if (session.owner.inFlight < 4) {
12606
+ for (const item of session.pending.values()) {
12607
+ if (!item.running && !session.owner.delivering.has(item.id)) next = Math.min(next, item.due);
12608
+ }
12609
+ }
12610
+ if (!session.checkpointTask && safePosition(session).order > session.durableOrder) {
12611
+ next = Math.min(next, session.checkpointDue);
12612
+ }
12613
+ if (next !== Infinity) {
12614
+ session.retryTimer = compatGlobal.setTimeout(bindContext(session, retry), Math.max(0, next - Date.now()));
12615
+ }
12616
+ }
12617
+ function retry(session) {
12618
+ session.retryTimer = void 0;
12619
+ void pump(session);
12620
+ }
12621
+ async function persistCheckpoint({ session, position, epoch, previous }) {
12622
+ if (previous) await previous;
12623
+ if (!isActive(session) || session.connection !== epoch) return;
12624
+ try {
12625
+ await session.onCheckpoint?.(position.seq);
12626
+ if (!isActive(session)) return;
12627
+ session.owner.host.state.since = String(position.seq);
12628
+ if (session.connection === epoch) session.durableOrder = position.order;
12629
+ session.checkpointFailures = 0;
12630
+ session.checkpointDue = 0;
12631
+ } catch (ex) {
12632
+ Logger19(`WATCH: CHECKPOINT FAILED`, LEVEL_INFO2, "watch");
12633
+ Logger19(ex, LEVEL_VERBOSE, "watch");
12634
+ if (isActive(session) && session.connection === epoch) {
12635
+ session.checkpointDue = Date.now() + retryDelay(++session.checkpointFailures);
12636
+ }
12637
+ }
12638
+ }
12639
+ function finishCheckpoint({ session, task }) {
12640
+ session.checkpointTask = void 0;
12641
+ if (session.owner.checkpointPending === task) session.owner.checkpointPending = void 0;
12642
+ if (isActive(session)) {
12643
+ void flushCheckpoint(session);
12644
+ schedule(session);
12645
+ }
12646
+ }
12647
+ function flushCheckpoint(session) {
12648
+ if (session.checkpointTask) return session.checkpointTask;
12649
+ if (!isActive(session) || !session.connected || Date.now() < session.checkpointDue) return Promise.resolve();
12650
+ const position = safePosition(session);
12651
+ if (position.order <= session.durableOrder) return Promise.resolve();
12652
+ const context = {
12653
+ session,
12654
+ position,
12655
+ epoch: session.connection,
12656
+ previous: session.owner.checkpointPending
12657
+ };
12658
+ const task = persistCheckpoint(context).finally(bindContext(context, finishCheckpoint));
12659
+ context.task = task;
12660
+ session.checkpointTask = task;
12661
+ session.owner.checkpointPending = task;
12662
+ return task;
12663
+ }
12664
+ function releaseDelivery({ session, item }) {
12665
+ session.owner.delivering.delete(item.id);
12666
+ }
12667
+ async function deliver(scope) {
12668
+ const { session, item, ready } = scope.value;
12669
+ session.owner.delivering.add(item.id);
12670
+ scope.defer(bindContext(scope.value, releaseDelivery));
12671
+ await session.callback(ready, item.seq);
12672
+ }
12673
+ async function processDocument(context) {
12674
+ const { session, item } = context;
12675
+ let loading = true;
12676
+ try {
12677
+ const doc = item.doc;
12678
+ if (isNoteEntry(doc) && (!session.checkIsInterested || session.checkIsInterested(doc))) {
12679
+ Logger19(`WATCH: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
12680
+ const ready = doc.deleted || doc._deleted ? { ...doc, data: [] } : await session.owner.host.readDocument(doc);
12681
+ if (!isCurrent(context)) return;
12682
+ loading = false;
12683
+ await withScope({ ...context, ready }, deliver);
12684
+ if (!isCurrent(context)) return;
12685
+ Logger19(`WATCH: PROCESS DONE: ${doc.path}`, LEVEL_INFO2, "watch");
12686
+ }
12687
+ if (!isCurrent(context)) return;
12688
+ session.pending.delete(item.id);
12689
+ void flushCheckpoint(session);
12690
+ } catch (ex) {
12691
+ if (!isCurrent(context)) return;
12692
+ Logger19(
12693
+ loading ? `WATCH: DOCUMENT LOAD FAILED: ${documentPath(item.doc)}` : `WATCH: PROCESS FAILED`,
12694
+ LEVEL_INFO2,
12695
+ "watch"
12696
+ );
12697
+ Logger19(ex, LEVEL_VERBOSE, "watch");
12698
+ item.due = Date.now() + retryDelay(++item.failures);
12699
+ }
12700
+ }
12701
+ function releaseFileOperation({ session, item }) {
12702
+ item.running = false;
12703
+ session.owner.inFlight--;
12704
+ if (session.owner.session) void pump(session.owner.session);
12705
+ }
12706
+ async function processFileOperation(scope) {
12707
+ scope.defer(bindContext(scope.value, releaseFileOperation));
12708
+ await processDocument(scope.value);
12709
+ }
12710
+ function pump(session) {
12711
+ if (!isActive(session) || !session.connected) return Promise.resolve();
12712
+ const tasks = [];
12713
+ for (const item of session.pending.values()) {
12714
+ if (session.owner.inFlight >= 4) break;
12715
+ if (item.running || item.due > Date.now() || session.owner.delivering.has(item.id)) continue;
12716
+ item.running = true;
12717
+ session.owner.inFlight++;
12718
+ tasks.push(withScope({ session, item, epoch: session.connection }, processFileOperation));
12719
+ }
12720
+ void flushCheckpoint(session);
12721
+ schedule(session);
12722
+ return Promise.all(tasks).then(() => {
12723
+ });
12724
+ }
12725
+ async function reconnectAfterCheckpoint(session) {
12726
+ session.reconnectTimer = void 0;
12727
+ if (session.checkpointTask) await session.checkpointTask;
12728
+ if (isActive(session)) connect(session);
12729
+ }
12730
+ function reconnect({ session, epoch }) {
12731
+ if (!isActive(session) || !session.connected || session.connection !== epoch) return;
12732
+ session.owner.host.state.watching = false;
12733
+ session.connected = false;
12734
+ session.connection++;
12735
+ cancelRetry(session);
12736
+ session.pending.clear();
12737
+ cancelFeed(session);
12738
+ Logger19(`WATCH: CONNECTION HAS BEEN CLOSED, RECONNECTING...`, LEVEL_INFO2, "watch");
12739
+ session.reconnectTimer = compatGlobal.setTimeout(bindContext(session, reconnectAfterCheckpoint), 1e4);
12740
+ }
12741
+ async function receiveChange({ session, epoch }, change) {
12742
+ if (!isActive(session) || !session.connected || session.connection !== epoch) return;
12743
+ const before = session.latest;
12744
+ session.latest = { order: before.order + 1, seq: change.seq };
12745
+ const id = change.id ?? change.doc?._id ?? documentPath(change.doc) ?? `row:${session.latest.order}`;
12746
+ const previous = session.pending.get(id);
12747
+ const doc = change.doc?._deleted && previous?.doc ? { ...previous.doc, ...change.doc } : change.doc;
12748
+ session.pending.set(id, {
12749
+ id,
12750
+ doc,
12751
+ seq: change.seq,
12752
+ before: previous?.before ?? before,
12753
+ running: false,
12754
+ failures: 0,
12755
+ due: 0
12756
+ });
12757
+ await pump(session);
12758
+ }
12759
+ function receiveError(context, error) {
12760
+ if (!isActive(context.session) || context.session.connection !== context.epoch) return;
12761
+ Logger19(`WATCH: ERROR: `, LEVEL_INFO2, "watch");
12762
+ Logger19(error, LEVEL_VERBOSE, "watch");
12763
+ reconnect(context);
12764
+ }
12765
+ function connect(session) {
12766
+ if (!isActive(session)) return;
12767
+ const context = { session, epoch: ++session.connection };
12768
+ const { state } = session.owner.host;
12769
+ state.watching = true;
12770
+ session.connected = true;
12771
+ session.latest = { order: 0, seq: state.since };
12772
+ session.durableOrder = 0;
12773
+ session.checkpointFailures = 0;
12774
+ session.checkpointDue = 0;
12775
+ try {
12776
+ state.changes = session.owner.host.openChanges(state.since).on("change", bindContext(context, receiveChange)).on("complete", bindContext(context, reconnect)).on("error", bindContext(context, receiveError));
12777
+ } catch (ex) {
12778
+ Logger19(`WATCH: ERROR: `, LEVEL_INFO2, "watch");
12779
+ Logger19(ex, LEVEL_VERBOSE, "watch");
12780
+ reconnect(context);
12781
+ }
11600
12782
  }
12783
+ var DirectFileWatchOwner = class {
12784
+ context;
12785
+ constructor(host) {
12786
+ this.context = { host, inFlight: 0, delivering: /* @__PURE__ */ new Set() };
12787
+ }
12788
+ beginWatch(callback, checkIsInterested, onCheckpoint) {
12789
+ if (this.context.session || this.context.host.state.watching) return false;
12790
+ const session = {
12791
+ owner: this.context,
12792
+ callback,
12793
+ checkIsInterested,
12794
+ onCheckpoint,
12795
+ pending: /* @__PURE__ */ new Map(),
12796
+ latest: { order: 0, seq: this.context.host.state.since },
12797
+ durableOrder: 0,
12798
+ connection: 0,
12799
+ connected: false,
12800
+ checkpointFailures: 0,
12801
+ checkpointDue: 0
12802
+ };
12803
+ this.context.session = session;
12804
+ connect(session);
12805
+ }
12806
+ endWatch() {
12807
+ if (this.context.session) stop(this.context.session);
12808
+ }
12809
+ };
12810
+
12811
+ // lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
11601
12812
  function isReadyEntry(doc) {
11602
12813
  if (!doc) return false;
11603
12814
  return "data" in doc;
@@ -11626,6 +12837,7 @@ var DirectFileManipulator = class {
11626
12837
  if (idCompatibility === "mismatched") {
11627
12838
  throw new Error("Direct database document IDs do not match the configured ID key.");
11628
12839
  }
12840
+ await assertDatabasePathIdentity(this.liveSyncLocalDB.localDatabase, idSettings);
11629
12841
  const requiredFeatures = requiredRemoteFeatures(this.settings);
11630
12842
  if (!await checkRemoteVersion(
11631
12843
  this.liveSyncLocalDB.localDatabase,
@@ -11663,6 +12875,7 @@ var DirectFileManipulator = class {
11663
12875
  const getSettings = () => this.settings;
11664
12876
  const context = new ServiceContext();
11665
12877
  this.services = new HeadlessServiceHub(context, {
12878
+ deviceValues: new MemoryValueStore(),
11666
12879
  pouchDB: PouchDB,
11667
12880
  database: this.getBoundDatabaseService(() => this.options, this.runtimeOptions),
11668
12881
  getPathObfuscationPassphrase: () => this.options.obfuscatePassphrase ?? false,
@@ -11678,7 +12891,9 @@ var DirectFileManipulator = class {
11678
12891
  });
11679
12892
  this.services.setting.settings = getSettings();
11680
12893
  this.services.databaseEvents.onDatabaseInitialisation.addHandler(this.$everyOnInitializeDatabase.bind(this));
11681
- this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this);
12894
+ this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this, {
12895
+ createChunkFetchSource: createDirectChunkFetchSource
12896
+ });
11682
12897
  void this.ready.promise.catch(() => {
11683
12898
  });
11684
12899
  void this.init();
@@ -11711,7 +12926,7 @@ var DirectFileManipulator = class {
11711
12926
  }
11712
12927
  return downloadedSyncParams;
11713
12928
  } catch (ex) {
11714
- Logger19(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO6);
12929
+ Logger20(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO6);
11715
12930
  throw SyncParamsFetchError.fromError(ex);
11716
12931
  }
11717
12932
  }
@@ -11723,7 +12938,7 @@ var DirectFileManipulator = class {
11723
12938
  }
11724
12939
  throw new SyncParamsUpdateError(`Could not store remote sync parameters`);
11725
12940
  } catch (ex) {
11726
- Logger19(`Could not store remote sync parameters`, LOG_LEVEL_INFO6);
12941
+ Logger20(`Could not store remote sync parameters`, LOG_LEVEL_INFO6);
11727
12942
  throw SyncParamsUpdateError.fromError(ex);
11728
12943
  }
11729
12944
  }
@@ -11747,7 +12962,8 @@ var DirectFileManipulator = class {
11747
12962
  false,
11748
12963
  async () => await this.getReplicationPBKDF2Salt(this.getSettings()),
11749
12964
  this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2,
11750
- usesEncryptedInternalMetadata(this.settings)
12965
+ usesEncryptedInternalMetadata(this.settings),
12966
+ this.options.acceptUnencryptedContent ?? false
11751
12967
  );
11752
12968
  }
11753
12969
  return Promise.resolve(true);
@@ -11756,6 +12972,7 @@ var DirectFileManipulator = class {
11756
12972
  return this.settings;
11757
12973
  }
11758
12974
  async close() {
12975
+ this.endWatch();
11759
12976
  await this.liveSyncLocalDB.close();
11760
12977
  return this.liveSyncLocalDB.onunload();
11761
12978
  }
@@ -11771,6 +12988,9 @@ var DirectFileManipulator = class {
11771
12988
  passphrase: this.options.passphrase ?? "",
11772
12989
  idDerivationVersion: this.options.idDerivationVersion ?? 0,
11773
12990
  idDerivationKey: this.options.idDerivationKey ?? "",
12991
+ pathNormalizationVersion: getPathNormalizationVersion({
12992
+ pathNormalizationVersion: this.options.pathNormalizationVersion
12993
+ }),
11774
12994
  deleteMetadataOfDeletedFiles: DEFAULT_SETTINGS.deleteMetadataOfDeletedFiles,
11775
12995
  customChunkSize: this.options.customChunkSize ?? DEFAULT_SETTINGS.customChunkSize,
11776
12996
  doNotPaceReplication: DEFAULT_SETTINGS.doNotPaceReplication,
@@ -11797,6 +13017,8 @@ var DirectFileManipulator = class {
11797
13017
  handleFilenameCaseSensitive: this.options.handleFilenameCaseSensitive ?? DEFAULT_SETTINGS.handleFilenameCaseSensitive,
11798
13018
  usePathObfuscation: !!this.options.obfuscatePassphrase,
11799
13019
  encryptInternalMetadata: this.options.encryptInternalMetadata ?? false,
13020
+ acceptUnencryptedContent: this.options.acceptUnencryptedContent ?? DEFAULT_SETTINGS.acceptUnencryptedContent,
13021
+ syncInternalFiles: this.options.syncInternalFiles ?? DEFAULT_SETTINGS.syncInternalFiles,
11800
13022
  E2EEAlgorithm: this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2
11801
13023
  }
11802
13024
  };
@@ -11871,24 +13093,24 @@ var DirectFileManipulator = class {
11871
13093
  children: [],
11872
13094
  datatype
11873
13095
  };
11874
- Logger19(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE21);
13096
+ Logger20(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE21);
11875
13097
  const ret = await this.liveSyncLocalDB.putDBEntry(putDoc);
11876
13098
  if (ret) {
11877
- Logger19(`PUT: DONE: ${path}`, LOG_LEVEL_INFO6);
13099
+ Logger20(`PUT: DONE: ${path}`, LOG_LEVEL_INFO6);
11878
13100
  return true;
11879
13101
  } else {
11880
- Logger19(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE9);
13102
+ Logger20(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE10);
11881
13103
  return false;
11882
13104
  }
11883
13105
  }
11884
13106
  async delete(path) {
11885
- Logger19(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE21);
13107
+ Logger20(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE21);
11886
13108
  const ret = await this.liveSyncLocalDB.deleteDBEntry(path);
11887
13109
  if (ret) {
11888
- Logger19(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO6);
13110
+ Logger20(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO6);
11889
13111
  return true;
11890
13112
  } else {
11891
- Logger19(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO6);
13113
+ Logger20(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO6);
11892
13114
  return false;
11893
13115
  }
11894
13116
  }
@@ -11916,81 +13138,60 @@ var DirectFileManipulator = class {
11916
13138
  }
11917
13139
  }
11918
13140
  watching = false;
11919
- // _abortController?: AbortController;
11920
13141
  changes;
11921
13142
  since = "";
11922
- beginWatch(callback, checkIsInterested) {
11923
- if (this.watching) return false;
11924
- this.watching = true;
11925
- this.changes = this.liveSyncLocalDB.localDatabase.changes({
11926
- include_docs: true,
11927
- since: this.since,
11928
- selector: {
11929
- type: { $ne: "leaf" }
11930
- },
11931
- live: true
11932
- }).on("change", async (change) => {
11933
- const doc = change.doc;
11934
- if (!doc) {
11935
- return;
11936
- }
11937
- if (!isNoteEntry(doc)) {
11938
- return;
11939
- }
11940
- if (checkIsInterested) {
11941
- if (!checkIsInterested(doc)) {
11942
- Logger19(`WATCH: SKIP ${doc.path}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE21, "watch");
11943
- return;
13143
+ watchOwner;
13144
+ /**
13145
+ * Watch file changes, retrying incomplete reads and rejected consumer callbacks.
13146
+ * Resolving the file callback acknowledges processing. The optional checkpoint
13147
+ * callback must resolve after the host has persisted its safe resume position.
13148
+ */
13149
+ beginWatch(callback, checkIsInterested, onCheckpoint) {
13150
+ const manipulator = this;
13151
+ this.watchOwner ??= new DirectFileWatchOwner({
13152
+ state: {
13153
+ get watching() {
13154
+ return manipulator.watching;
13155
+ },
13156
+ set watching(value) {
13157
+ manipulator.watching = value;
13158
+ },
13159
+ get changes() {
13160
+ return manipulator.changes;
13161
+ },
13162
+ set changes(value) {
13163
+ manipulator.changes = value;
13164
+ },
13165
+ get since() {
13166
+ return manipulator.since;
13167
+ },
13168
+ set since(value) {
13169
+ manipulator.since = value;
11944
13170
  }
11945
- }
11946
- Logger19(`WATCH: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
11947
- let docX;
11948
- try {
11949
- docX = await this.getByMeta(doc);
11950
- } catch (ex) {
11951
- Logger19(`WATCH: DOCUMENT LOAD FAILED: ${doc.path}`, LEVEL_INFO2, "watch");
11952
- Logger19(ex, LEVEL_VERBOSE, "watch");
11953
- return;
11954
- }
11955
- try {
11956
- await callback(docX, change.seq);
11957
- Logger19(`WATCH: PROCESS DONE: ${doc.path}`, LEVEL_INFO2, "watch");
11958
- } catch (ex) {
11959
- Logger19(`WATCH: PROCESS FAILED`, LEVEL_INFO2, "watch");
11960
- Logger19(ex, LEVEL_VERBOSE, "watch");
11961
- }
11962
- }).on("complete", () => {
11963
- Logger19(`WATCH: FINISHED`, LEVEL_INFO2, "watch");
11964
- this.watching = false;
11965
- this.changes = void 0;
11966
- }).on("error", (err) => {
11967
- Logger19(`WATCH: ERROR: `, LEVEL_INFO2, "watch");
11968
- Logger19(err, LEVEL_VERBOSE, "watch");
11969
- if (this.watching) {
11970
- Logger19(`WATCH: CONNECTION HAS BEEN CLOSED, RECONNECTING...`, LEVEL_INFO2, "watch");
11971
- this.watching = false;
11972
- this.changes = void 0;
11973
- compatGlobal.setTimeout(() => {
11974
- this.beginWatch(callback, checkIsInterested);
11975
- }, 1e4);
11976
- } else {
11977
- Logger19(`WATCH: CONNECTION HAS BEEN CLOSED.`, LEVEL_INFO2, "watch");
13171
+ },
13172
+ openChanges(since) {
13173
+ return manipulator.liveSyncLocalDB.localDatabase.changes({
13174
+ include_docs: true,
13175
+ since,
13176
+ selector: { type: { $ne: "leaf" } },
13177
+ live: true
13178
+ });
13179
+ },
13180
+ readDocument(doc) {
13181
+ return manipulator.getByMeta(doc);
11978
13182
  }
11979
13183
  });
13184
+ return this.watchOwner.beginWatch(callback, checkIsInterested, onCheckpoint);
11980
13185
  }
11981
13186
  endWatch() {
11982
- if (this.changes) {
11983
- Logger19(`WATCH: CANCELLING PROCESS.`, LEVEL_INFO2, "watch");
11984
- this.changes.cancel();
11985
- Logger19(`WATCH: CANCELLING SIGNAL HAS BEEN SENT.`, LEVEL_INFO2, "watch");
11986
- }
13187
+ this.watchOwner?.endWatch();
11987
13188
  }
11988
13189
  async followUpdates(callback, checkIsInterested) {
11989
13190
  try {
11990
13191
  if (this.since == "") {
11991
13192
  this.since = "0";
11992
13193
  }
11993
- Logger19(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO2, "followUpdates");
13194
+ Logger20(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO3, "followUpdates");
11994
13195
  const last = await this.liveSyncLocalDB.localDatabase.changes({
11995
13196
  include_docs: true,
11996
13197
  since: this.since,
@@ -12006,29 +13207,29 @@ var DirectFileManipulator = class {
12006
13207
  }
12007
13208
  if (checkIsInterested) {
12008
13209
  if (!checkIsInterested(doc)) {
12009
- Logger19(`FOLLOW: SKIP ${doc._id}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE21, "watch");
13210
+ Logger20(`FOLLOW: SKIP ${doc._id}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE21, "watch");
12010
13211
  return;
12011
13212
  }
12012
13213
  }
12013
- Logger19(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
13214
+ Logger20(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE2, "watch");
12014
13215
  const docX = await this.getByMeta(doc);
12015
13216
  try {
12016
13217
  await callback(docX, change.seq);
12017
- Logger19(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO2, "watch");
13218
+ Logger20(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO3, "watch");
12018
13219
  } catch (ex) {
12019
- Logger19(`FOLLOW: PROCESS FAILED`, LEVEL_INFO2, "watch");
12020
- Logger19(ex, LEVEL_VERBOSE, "watch");
13220
+ Logger20(`FOLLOW: PROCESS FAILED`, LEVEL_INFO3, "watch");
13221
+ Logger20(ex, LEVEL_VERBOSE2, "watch");
12021
13222
  }
12022
13223
  }).on("complete", () => {
12023
- Logger19(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO2, "watch");
13224
+ Logger20(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO3, "watch");
12024
13225
  this.watching = false;
12025
13226
  this.changes = void 0;
12026
13227
  }).on("error", (err) => {
12027
- Logger19(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO2, "watch");
13228
+ Logger20(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO3, "watch");
12028
13229
  });
12029
13230
  return last.last_seq;
12030
13231
  } catch (e) {
12031
- Logger19(`FOLLOW: ERROR: ${e}`, LEVEL_INFO2, "watch");
13232
+ Logger20(`FOLLOW: ERROR: ${e}`, LEVEL_INFO3, "watch");
12032
13233
  }
12033
13234
  return this.since;
12034
13235
  }
@@ -12037,6 +13238,38 @@ var DirectFileManipulator = class {
12037
13238
  // src/vault.ts
12038
13239
  import { isPathProbablyObfuscated as isPathProbablyObfuscated2, decrypt as decrypt4 } from "octagonal-wheels/encryption/encryption";
12039
13240
 
13241
+ // src/keyed-lock.ts
13242
+ var KeyedLock = class {
13243
+ tails = /* @__PURE__ */ new Map();
13244
+ /** Run `fn` once every earlier holder of any of `keys` has finished. */
13245
+ async run(keys, fn) {
13246
+ const unique5 = [...new Set(keys)].sort();
13247
+ const releases = [];
13248
+ try {
13249
+ for (const key of unique5) releases.push(await this.acquire(key));
13250
+ return await fn();
13251
+ } finally {
13252
+ for (const release of releases.reverse()) release();
13253
+ }
13254
+ }
13255
+ async acquire(key) {
13256
+ const previous = this.tails.get(key) ?? Promise.resolve();
13257
+ let release;
13258
+ const current = new Promise((r) => release = r);
13259
+ const tail = previous.then(() => current);
13260
+ this.tails.set(key, tail);
13261
+ await previous;
13262
+ return () => {
13263
+ release();
13264
+ if (this.tails.get(key) === tail) this.tails.delete(key);
13265
+ };
13266
+ }
13267
+ /** Keys currently held or queued (for tests). */
13268
+ get size() {
13269
+ return this.tails.size;
13270
+ }
13271
+ };
13272
+
12040
13273
  // src/id-derivation-config.ts
12041
13274
  function idDerivationOptions(obfuscatePaths, idDerivationKey) {
12042
13275
  if (obfuscatePaths && idDerivationKey) {
@@ -12118,11 +13351,17 @@ var Vault = class _Vault {
12118
13351
  // Obfuscation actually in effect after reconciling with the database, which
12119
13352
  // can differ from the configured value.
12120
13353
  obfuscatePathsEffective = false;
13354
+ // Path identity declared by the database: 0 = legacy, 1 = Unicode NFC
13355
+ // (`nfc-path-identity-v1`, the default for databases created by LiveSync
13356
+ // 1.0.49+). Detected in init(); the library rejects a mismatch.
13357
+ pathNormalizationVersion = 0;
13358
+ // Serializes attachment writes per document id (see writeAttachmentUnlocked).
13359
+ attachmentLock = new KeyedLock();
12121
13360
  constructor(config) {
12122
13361
  this.config = config;
12123
13362
  this.passphrase = config.passphrase;
12124
13363
  }
12125
- static buildOptions(config, obfuscatePaths, idDerivationKey) {
13364
+ static buildOptions(config, obfuscatePaths, idDerivationKey, pathNormalizationVersion) {
12126
13365
  return {
12127
13366
  url: config.couchdbUrl,
12128
13367
  username: config.couchdbUser,
@@ -12134,6 +13373,7 @@ var Vault = class _Vault {
12134
13373
  enableCompression: false,
12135
13374
  handleFilenameCaseSensitive: !!config.caseSensitive,
12136
13375
  doNotUseFixedRevisionForChunks: false,
13376
+ pathNormalizationVersion,
12137
13377
  ...idDerivationOptions(obfuscatePaths, idDerivationKey)
12138
13378
  };
12139
13379
  }
@@ -12148,7 +13388,11 @@ var Vault = class _Vault {
12148
13388
  username: this.config.couchdbUser,
12149
13389
  password: this.config.couchdbPassword
12150
13390
  });
12151
- this.manipulator = new DirectFileManipulator(_Vault.buildOptions(this.config, this.obfuscatePathsEffective, this.idDerivationKey));
13391
+ const pathIdentity = resolvePathIdentity(this.config.pathNormalization ?? "auto", await this.inspectPathIdentity());
13392
+ this.pathNormalizationVersion = pathIdentity.version;
13393
+ if (pathIdentity.notice) console.warn(pathIdentity.notice);
13394
+ else if (pathIdentity.version === 1) console.log("Vault uses Unicode NFC path identity (nfc-path-identity-v1).");
13395
+ this.manipulator = new DirectFileManipulator(this.options(this.obfuscatePathsEffective));
12152
13396
  await this.awaitManipulatorReady();
12153
13397
  await this.reconcileObfuscation();
12154
13398
  if (this.idDerivationKey && !this.obfuscatePathsEffective) {
@@ -12157,6 +13401,26 @@ var Vault = class _Vault {
12157
13401
  );
12158
13402
  }
12159
13403
  }
13404
+ options(obfuscatePaths) {
13405
+ return _Vault.buildOptions(this.config, obfuscatePaths, this.idDerivationKey, this.pathNormalizationVersion);
13406
+ }
13407
+ /**
13408
+ * Read the database's path identity declaration (legacy vs Unicode NFC)
13409
+ * so the manipulator is opened with the matching setting. Read-only: it
13410
+ * never declares a feature itself; DirectFileManipulator then declares the
13411
+ * chosen identity in an empty database when it opens it.
13412
+ */
13413
+ async inspectPathIdentity() {
13414
+ const db = new PouchDB(`${this.config.couchdbUrl.replace(/\/+$/, "")}/${this.config.database}`, {
13415
+ auth: { username: this.config.couchdbUser, password: this.config.couchdbPassword },
13416
+ skip_setup: true
13417
+ });
13418
+ try {
13419
+ return await inspectDatabasePathIdentity(db);
13420
+ } finally {
13421
+ await db.close();
13422
+ }
13423
+ }
12160
13424
  /**
12161
13425
  * Await the manipulator's readiness, translating the library's ID-mismatch
12162
13426
  * error into actionable guidance. The library (0.1.34+) verifies at startup
@@ -12203,8 +13467,8 @@ var Vault = class _Vault {
12203
13467
  actual ? "Warning: vault uses obfuscated document IDs but COUCHDB_OBFUSCATE_PROPERTIES is not set to true. Enabling path obfuscation automatically \u2014 set COUCHDB_OBFUSCATE_PROPERTIES=true to silence this warning." : "Warning: COUCHDB_OBFUSCATE_PROPERTIES=true but vault uses plaintext document IDs. Disabling path obfuscation automatically \u2014 set COUCHDB_OBFUSCATE_PROPERTIES=false to silence this warning."
12204
13468
  );
12205
13469
  this.obfuscatePathsEffective = actual;
12206
- await this.manipulator.close();
12207
- this.manipulator = new DirectFileManipulator(_Vault.buildOptions(this.config, actual, this.idDerivationKey));
13470
+ await _Vault.closeManipulator(this.manipulator);
13471
+ this.manipulator = new DirectFileManipulator(this.options(actual));
12208
13472
  await this.awaitManipulatorReady();
12209
13473
  }
12210
13474
  /** Sample file-entry docs from the changes feed and classify their IDs. */
@@ -12232,8 +13496,25 @@ var Vault = class _Vault {
12232
13496
  return classifyIds(ids);
12233
13497
  }
12234
13498
  async close() {
12235
- this.manipulator.endWatch();
12236
- await this.manipulator.close();
13499
+ await _Vault.closeManipulator(this.manipulator);
13500
+ }
13501
+ /**
13502
+ * Close a manipulator and stop its internal changes feed. The library tears
13503
+ * its managers down on PouchDB's "close" event, but PouchDB emits "closed",
13504
+ * so without this the feed outlives close() and keeps decrypting incoming
13505
+ * changes. After clearHandlers() that dead instance can win the race to
13506
+ * re-create the shared sync-parameters handler, binding it to a closed
13507
+ * database: every later salt fetch then fails. Reproduced as an
13508
+ * intermittent crash in the CouchDB harness; the reopen in
13509
+ * reconcileObfuscation is exposed to the same race.
13510
+ */
13511
+ static async closeManipulator(manipulator) {
13512
+ manipulator.endWatch();
13513
+ try {
13514
+ await manipulator.liveSyncLocalDB.managers.teardownManagers();
13515
+ } catch {
13516
+ }
13517
+ await manipulator.close();
12237
13518
  }
12238
13519
  static mdFilter(meta) {
12239
13520
  return isValidNotePath(meta.path ?? "");
@@ -12244,7 +13525,7 @@ var Vault = class _Vault {
12244
13525
  const content = deriveContent(doc);
12245
13526
  callback(path, content, content === null ? void 0 : doc.mtime, seq);
12246
13527
  }
12247
- async catchUp(since, callback, onBatch, stats) {
13528
+ async catchUp(since, callback, onBatch, stats, onAttachment) {
12248
13529
  const BATCH_SIZE2 = 50;
12249
13530
  const db = this.manipulator.liveSyncLocalDB.localDatabase;
12250
13531
  let currentSince = since;
@@ -12271,6 +13552,10 @@ var Vault = class _Vault {
12271
13552
  continue;
12272
13553
  }
12273
13554
  }
13555
+ if (onAttachment && isValidAttachmentPath(path)) {
13556
+ onAttachment(path, meta.deleted ? null : { size: meta.size ?? 0, mtime: meta.mtime ?? 0 });
13557
+ continue;
13558
+ }
12274
13559
  if (meta.deleted) {
12275
13560
  if (isValidNotePath(path)) callback(path, null);
12276
13561
  continue;
@@ -12294,12 +13579,29 @@ var Vault = class _Vault {
12294
13579
  this.manipulator.since = currentSince;
12295
13580
  return currentSince;
12296
13581
  }
12297
- watchChanges(callback) {
13582
+ watchChanges(callback, onAttachment) {
13583
+ const filter = (meta) => {
13584
+ if (onAttachment) this.reportAttachment(meta, onAttachment);
13585
+ return _Vault.mdFilter(meta);
13586
+ };
12298
13587
  this.manipulator.beginWatch(
12299
13588
  (doc, seq) => _Vault.docToChange(doc, callback, seq),
12300
- _Vault.mdFilter
13589
+ filter
12301
13590
  );
12302
13591
  }
13592
+ reportAttachment(meta, onAttachment) {
13593
+ const emit = (path2) => {
13594
+ if (!isValidAttachmentPath(path2)) return;
13595
+ onAttachment(path2, meta.deleted ? null : { size: meta.size ?? 0, mtime: meta.mtime ?? 0 });
13596
+ };
13597
+ const path = meta.path ?? "";
13598
+ if (isPathProbablyObfuscated2(path) && this.passphrase) {
13599
+ decrypt4(path, this.passphrase, false).then(emit, () => {
13600
+ });
13601
+ } else {
13602
+ emit(path);
13603
+ }
13604
+ }
12303
13605
  validatePath(path) {
12304
13606
  validateNotePath(path);
12305
13607
  }
@@ -12337,8 +13639,11 @@ var Vault = class _Vault {
12337
13639
  this.validatePath(to);
12338
13640
  const content = await this.readNote(from);
12339
13641
  if (content === null) return false;
13642
+ if (from === to) return true;
12340
13643
  const wrote = await this.writeNote(to, content);
12341
13644
  if (!wrote) return false;
13645
+ const fromId = await this.manipulator.path2id(from);
13646
+ if (fromId === await this.manipulator.path2id(to)) return true;
12342
13647
  return await this.deleteNote(from);
12343
13648
  }
12344
13649
  async getMetadata(path) {
@@ -12371,8 +13676,83 @@ var Vault = class _Vault {
12371
13676
  }
12372
13677
  return results.sort((a, b) => a.path.localeCompare(b.path));
12373
13678
  }
13679
+ async writeAttachment(path, data, options = {}) {
13680
+ validateAttachmentPath(path);
13681
+ const id = await this.manipulator.path2id(path);
13682
+ return await this.attachmentLock.run([id], () => this.writeAttachmentUnlocked(path, data, options));
13683
+ }
13684
+ /**
13685
+ * The library's put always writes over the current revision, so "create
13686
+ * unless it exists" can't be one CouchDB request. Callers hold the
13687
+ * document's lock instead, which covers writes made by this server; a
13688
+ * concurrent write from Obsidian is left to LiveSync's conflict handling.
13689
+ */
13690
+ async writeAttachmentUnlocked(path, data, { overwrite = false }) {
13691
+ clearHandlers();
13692
+ let ctime = Date.now();
13693
+ const existing = await this.manipulator.get(path, true);
13694
+ if (existing && !overwrite) throw new AttachmentExistsError(path);
13695
+ if (existing && "ctime" in existing) {
13696
+ ctime = existing.ctime;
13697
+ }
13698
+ const blob = createBinaryBlob(new Uint8Array(data));
13699
+ return await this.manipulator.put(path, blob, {
13700
+ ctime,
13701
+ mtime: Date.now(),
13702
+ size: data.byteLength
13703
+ });
13704
+ }
13705
+ async deleteAttachment(path) {
13706
+ validateAttachmentPath(path);
13707
+ const id = await this.manipulator.path2id(path);
13708
+ return await this.attachmentLock.run([id], async () => {
13709
+ clearHandlers();
13710
+ return await this.manipulator.delete(path);
13711
+ });
13712
+ }
13713
+ async moveAttachment(from, to, { maxBytes, ...options } = {}) {
13714
+ validateAttachmentPath(from);
13715
+ validateAttachmentPath(to);
13716
+ const fromId = await this.manipulator.path2id(from);
13717
+ const toId = await this.manipulator.path2id(to);
13718
+ return await this.attachmentLock.run([fromId, toId], async () => {
13719
+ const meta = await this.manipulator.get(from, true);
13720
+ if (!meta) return false;
13721
+ if (from === to) return true;
13722
+ if (maxBytes !== void 0 && !(Number.isFinite(meta.size) && meta.size <= maxBytes)) {
13723
+ throw new AttachmentTooLargeError(from, meta.size, maxBytes);
13724
+ }
13725
+ if (fromId !== toId && !options.overwrite && await this.manipulator.get(to, true)) {
13726
+ throw new AttachmentExistsError(to);
13727
+ }
13728
+ const entry = await this.manipulator.get(from);
13729
+ if (!entry || !("data" in entry)) return false;
13730
+ const content = readContent(entry);
13731
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : new Uint8Array(content);
13732
+ if (maxBytes !== void 0 && bytes.byteLength > maxBytes) throw new AttachmentTooLargeError(from, bytes.byteLength, maxBytes);
13733
+ if (fromId === toId) {
13734
+ return await this.writeAttachmentUnlocked(to, bytes, { overwrite: true });
13735
+ }
13736
+ const wrote = await this.writeAttachmentUnlocked(to, bytes, options);
13737
+ if (!wrote) return false;
13738
+ clearHandlers();
13739
+ let deleted = false;
13740
+ try {
13741
+ deleted = await this.manipulator.delete(from);
13742
+ } catch {
13743
+ }
13744
+ if (!deleted) throw new AttachmentMoveIncompleteError(from, to);
13745
+ return true;
13746
+ });
13747
+ }
13748
+ async getAttachmentInfo(path) {
13749
+ validateAttachmentPath(path);
13750
+ const entry = await this.manipulator.get(path, true);
13751
+ if (!entry) return null;
13752
+ return { path, size: entry.size, ctime: entry.ctime, mtime: entry.mtime };
13753
+ }
12374
13754
  };
12375
13755
  export {
12376
13756
  Vault
12377
13757
  };
12378
- //# sourceMappingURL=vault-6H64Y46A.js.map
13758
+ //# sourceMappingURL=vault-XZDTCOVA.js.map