obsidian-sync-mcp 0.11.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,8 +2,9 @@
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 {
8
9
  AttachmentExistsError,
9
10
  AttachmentMoveIncompleteError,
@@ -16,6 +17,20 @@ import {
16
17
  validateNotePath
17
18
  } from "./chunk-XZ4HUASL.js";
18
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
+ }
33
+
19
34
  // lib/livesync-commonlib/src/common/types.ts
20
35
  import {
21
36
  LOG_LEVEL_DEBUG,
@@ -28,6 +43,8 @@ import { RESULT_NOT_FOUND, RESULT_TIMED_OUT } from "octagonal-wheels/common/cons
28
43
 
29
44
  // lib/livesync-commonlib/src/common/models/db.const.ts
30
45
  var VERSIONING_DOCID = "obsydian_livesync_version";
46
+ var MILESTONE_DOCID = "_local/obsydian_livesync_milestone";
47
+ var NODEINFO_DOCID = "_local/obsydian_livesync_nodeinfo";
31
48
  var SYNCINFO_ID = "syncinfo";
32
49
  var EntryTypes = {
33
50
  NOTE_LEGACY: "notes",
@@ -64,7 +81,6 @@ var IDPrefixes = {
64
81
  EncryptedChunk: "h:+"
65
82
  };
66
83
  var PREFIX_OBFUSCATED = "f:";
67
- var PREFIX_ENCRYPTED_CHUNK = "h:+";
68
84
 
69
85
  // lib/livesync-commonlib/src/common/models/setting.const.ts
70
86
  var SETTING_VERSION_INITIAL = 0;
@@ -131,6 +147,7 @@ function normaliseP2PConnectionPath(value) {
131
147
  // lib/livesync-commonlib/src/common/models/setting.const.preferred.ts
132
148
  var PREFERRED_BASE = {
133
149
  syncMaxSizeInMB: 50,
150
+ customChunkSize: 0,
134
151
  chunkSplitterVersion: "v3-rabin-karp",
135
152
  usePluginSyncV2: true,
136
153
  handleFilenameCaseSensitive: false,
@@ -138,21 +155,18 @@ var PREFERRED_BASE = {
138
155
  };
139
156
  var PREFERRED_SETTING_CLOUDANT = {
140
157
  ...PREFERRED_BASE,
141
- customChunkSize: 0,
142
158
  sendChunksBulkMaxSize: 1,
143
159
  concurrencyOfReadChunksOnline: 100,
144
160
  minimumIntervalOfReadChunksOnline: 333
145
161
  };
146
162
  var PREFERRED_SETTING_SELF_HOSTED = {
147
163
  ...PREFERRED_BASE,
148
- customChunkSize: 60,
149
164
  sendChunksBulkMaxSize: 1,
150
165
  concurrencyOfReadChunksOnline: 30,
151
166
  minimumIntervalOfReadChunksOnline: 25
152
167
  };
153
168
  var PREFERRED_JOURNAL_SYNC = {
154
169
  ...PREFERRED_BASE,
155
- customChunkSize: 10,
156
170
  concurrencyOfReadChunksOnline: 30,
157
171
  minimumIntervalOfReadChunksOnline: 25
158
172
  };
@@ -190,8 +204,10 @@ var SETTINGS_SCHEMA_DEFAULTS = {
190
204
  couchDB_PASSWORD: "",
191
205
  couchDB_DBNAME: "",
192
206
  liveSync: false,
207
+ batchSaveInLiveSync: false,
193
208
  syncOnSave: false,
194
209
  syncOnStart: false,
210
+ strictContentCheckOnStartup: false,
195
211
  savingDelay: 200,
196
212
  lessInformationInLog: false,
197
213
  gcDelay: 300,
@@ -205,9 +221,11 @@ var SETTINGS_SCHEMA_DEFAULTS = {
205
221
  periodicReplicationInterval: 60,
206
222
  syncOnFileOpen: false,
207
223
  encrypt: false,
224
+ acceptUnencryptedContent: false,
208
225
  passphrase: "",
209
226
  idDerivationVersion: 0,
210
227
  idDerivationKey: "",
228
+ pathNormalizationVersion: 0,
211
229
  usePathObfuscation: false,
212
230
  encryptInternalMetadata: false,
213
231
  doNotDeleteFolder: false,
@@ -336,6 +354,7 @@ var SETTINGS_SCHEMA_DEFAULTS = {
336
354
  jwtSub: "",
337
355
  jwtExpDuration: 5,
338
356
  useRequestAPI: false,
357
+ useCouchDBCacheControlHeadersOnly: false,
339
358
  bucketPrefix: "",
340
359
  chunkSplitterVersion: ChunkAlgorithms.RabinKarp,
341
360
  E2EEAlgorithm: E2EEAlgorithms.V2,
@@ -362,6 +381,11 @@ function createNewVaultSettings() {
362
381
  }
363
382
  var DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;
364
383
 
384
+ // lib/livesync-commonlib/src/common/models/setting.encryption.ts
385
+ function normaliseAcceptUnencryptedContent(value) {
386
+ return value === true;
387
+ }
388
+
365
389
  // lib/livesync-commonlib/src/common/models/setting.lifecycle.ts
366
390
  var SettingsMigrationReviewCodes = {
367
391
  LegacyUpdatePending: "legacy-update-review-pending",
@@ -431,8 +455,10 @@ function prepareSettingsForLoad(storedSettings) {
431
455
  toVersion: CURRENT_SETTING_VERSION
432
456
  }
433
457
  ];
458
+ const settings = cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS);
459
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(source.acceptUnencryptedContent);
434
460
  return {
435
- settings: cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS),
461
+ settings,
436
462
  sourceVersion,
437
463
  targetVersion: sourceVersion,
438
464
  isNewVault: false,
@@ -466,13 +492,15 @@ function prepareSettingsForLoad(storedSettings) {
466
492
  if (normalisedFilenameCase) migrated = { ...migrated, handleFilenameCaseSensitive: false };
467
493
  const normalisedInternalMetadata = typeof migrated.encryptInternalMetadata !== "boolean";
468
494
  if (normalisedInternalMetadata) migrated = { ...migrated, encryptInternalMetadata: false };
495
+ const normalisedAcceptUnencryptedContent = typeof migrated.acceptUnencryptedContent !== "boolean";
496
+ if (normalisedAcceptUnencryptedContent) migrated = { ...migrated, acceptUnencryptedContent: false };
469
497
  return {
470
498
  settings: cloneSettings(migrated, SETTINGS_SCHEMA_DEFAULTS),
471
499
  sourceVersion,
472
500
  targetVersion,
473
501
  isNewVault: false,
474
502
  isFromFutureSchema: false,
475
- changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata,
503
+ changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata || normalisedAcceptUnencryptedContent,
476
504
  requiresSyncReview: reviewReasons.length > 0,
477
505
  reviewReasons
478
506
  };
@@ -509,6 +537,7 @@ var TweakCompatibilityRules = Object.freeze([
509
537
  { key: "encrypt", templateValue: false, reconstruction: "required" },
510
538
  { key: "usePathObfuscation", templateValue: false, reconstruction: "required" },
511
539
  { key: "idDerivationVersion", templateValue: 0, reconstruction: "required", knownDefault: 0 },
540
+ { key: "pathNormalizationVersion", templateValue: 0, reconstruction: "required", knownDefault: 0 },
512
541
  { key: "encryptInternalMetadata", templateValue: false, reconstruction: "none", knownDefault: false },
513
542
  { key: "enableCompression", templateValue: false, reconstruction: "none" },
514
543
  { key: "useEden", templateValue: false, reconstruction: "none" },
@@ -799,14 +828,35 @@ async function computeKeyedId(key, purpose, value) {
799
828
  return uint8ArrayToHexString(new Uint8Array(digest));
800
829
  }
801
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
+
802
846
  // lib/livesync-commonlib/src/pouchdb/remoteFeatureCompatibility.ts
803
847
  var REMOTE_FEATURE_GENERATION = 13;
804
848
  var ENCRYPTED_INTERNAL_METADATA_FEATURE = "encrypted-internal-metadata-v1";
805
849
  var INDEPENDENT_ID_DERIVATION_FEATURE = "independent-id-derivation-v1";
806
- 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
+ ]);
807
856
  function requiredRemoteFeatures(setting) {
808
857
  const features = [];
809
858
  if (usesEncryptedInternalMetadata(setting)) features.push(ENCRYPTED_INTERNAL_METADATA_FEATURE);
859
+ if (getPathNormalizationVersion(setting) === 1) features.push(NFC_PATH_IDENTITY_FEATURE);
810
860
  if (setting.encrypt && configuredIdKey(setting)) features.push(INDEPENDENT_ID_DERIVATION_FEATURE);
811
861
  return features;
812
862
  }
@@ -976,6 +1026,75 @@ async function assessRemoteDocumentIds(db, setting, path2id) {
976
1026
  return matched ? "matching" : "unverified";
977
1027
  }
978
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
+
979
1098
  // lib/livesync-commonlib/src/pouchdb/pouchdb-http.ts
980
1099
  import PouchDB from "pouchdb-core";
981
1100
  import HttpPouch from "pouchdb-adapter-http";
@@ -983,11 +1102,12 @@ import mapreduce from "pouchdb-mapreduce";
983
1102
  import replication from "pouchdb-replication";
984
1103
  import find from "pouchdb-find";
985
1104
  import transform from "transform-pouch";
1105
+
1106
+ // lib/livesync-commonlib/src/pouchdb/purgeMulti.ts
986
1107
  import { findPathToLeaf } from "pouchdb-merge";
987
1108
  import { adapterFun } from "pouchdb-utils";
988
1109
  import { createError, MISSING_DOC, UNKNOWN_ERROR } from "pouchdb-errors";
989
1110
  import { mapAllTasksWithConcurrencyLimit, unwrapTaskResult } from "octagonal-wheels/concurrency/task";
990
- PouchDB.plugin(HttpPouch).plugin(mapreduce).plugin(replication).plugin(find).plugin(transform);
991
1111
  function appendPurgeSeqs(db, docs) {
992
1112
  return db.get("_local/purges").then(function(doc) {
993
1113
  for (const [docId, rev$$1] of docs) {
@@ -1020,54 +1140,110 @@ function appendPurgeSeqs(db, docs) {
1020
1140
  return db.put(doc);
1021
1141
  });
1022
1142
  }
1023
- PouchDB.prototype.purgeMulti = adapterFun(
1024
- "_purgeMulti",
1025
- function(docs, callback) {
1026
- if (typeof this._purge === "undefined") {
1027
- return callback(
1028
- //@ts-ignore: this ts-ignore might be hiding a `this` bug where we don't have "this" conext.
1029
- createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter.")
1030
- );
1031
- }
1032
- const self = this;
1033
- const tasks = docs.map(
1034
- (param) => () => new Promise((res, rej) => {
1035
- const [docId, rev$$1] = param;
1036
- self._getRevisionTree(docId, (error, revs) => {
1037
- if (error) {
1038
- return res([param, error]);
1039
- }
1040
- if (!revs) {
1041
- return res([param, createError(MISSING_DOC)]);
1042
- }
1043
- let path;
1044
- try {
1045
- path = findPathToLeaf(revs, rev$$1);
1046
- } catch (error2) {
1047
- return res([param, error2.message || error2]);
1048
- }
1049
- self._purge(docId, path, (error2, result) => {
1050
- if (error2) {
1051
- return res([param, error2]);
1052
- } else {
1053
- 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)]);
1054
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
+ });
1055
1177
  });
1056
- });
1057
- })
1058
- );
1059
- (async () => {
1060
- const ret = await mapAllTasksWithConcurrencyLimit(1, tasks);
1061
- const retAll = ret.map((e) => unwrapTaskResult(e));
1062
- await appendPurgeSeqs(
1063
- self,
1064
- retAll.filter((e) => "ok" in e[1]).map((e) => e[0])
1178
+ })
1065
1179
  );
1066
- const result = Object.fromEntries(retAll.map((e) => [e[0][0], e[1]]));
1067
- return result;
1068
- })().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;
1069
1217
  }
1070
- );
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
+ }
1071
1247
 
1072
1248
  // lib/livesync-commonlib/src/managers/ChunkFetcher.ts
1073
1249
  import { delay, promiseWithResolvers as promiseWithResolvers2 } from "octagonal-wheels/promises";
@@ -1235,7 +1411,7 @@ function decideMissingChunkAction({
1235
1411
  }
1236
1412
  function isValidChunk(chunk) {
1237
1413
  const candidate = chunk;
1238
- 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";
1239
1415
  }
1240
1416
  function classifyFetchedChunks(requestedIds, fetched) {
1241
1417
  const chunks = [];
@@ -1498,7 +1674,11 @@ var ChunkFetcher = class {
1498
1674
  logger_exports.LOG_LEVEL_VERBOSE
1499
1675
  );
1500
1676
  for (const chunk of invalidChunks) {
1501
- (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
+ );
1502
1682
  }
1503
1683
  }
1504
1684
  if (chunks.length === 0) {
@@ -1574,20 +1754,25 @@ var ChunkFetcher = class {
1574
1754
  await this.resolveLocallyAvailableRetries(requestClaims);
1575
1755
  let pendingIDs = await this.waitBeforeRemoteRequest(requestIDs, requestClaims, localCheckCompletionVersion);
1576
1756
  if (pendingIDs.length === 0) return;
1577
- const replicator = this.options.replicatorService.getActiveReplicator();
1578
- if (!replicator) {
1579
- (0, logger_exports.Logger)("No active replicator was found to request missing chunks.");
1580
- return;
1581
- }
1582
- if (!canFetchRemoteChunks(replicator)) {
1583
- (0, logger_exports.Logger)("The active replicator does not support fetching individual remote chunks.");
1584
- for (const chunkID of pendingIDs) {
1585
- 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;
1586
1766
  }
1587
- 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);
1588
1775
  }
1589
- const requestCompletionVersion = this.finiteCompletionVersion;
1590
- const fetched = await replicator.fetchRemoteChunks(pendingIDs, false);
1591
1776
  pendingIDs = this.getActiveClaimIds(pendingIDs, requestClaims);
1592
1777
  this.touchClaims(pendingIDs, requestClaims);
1593
1778
  if (!fetched) {
@@ -1601,7 +1786,9 @@ var ChunkFetcher = class {
1601
1786
  this.logFetchedChunks(pendingIDs, classification);
1602
1787
  const { chunks, missingIds, invalidIds } = classification;
1603
1788
  try {
1604
- 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) {
1605
1792
  (0, logger_exports.Logger)(`Writing fetched chunks (${chunks.length}) to the database...`);
1606
1793
  const result = await this.chunkManager.write(
1607
1794
  chunks,
@@ -1637,8 +1824,22 @@ var ChunkFetcher = class {
1637
1824
  }
1638
1825
  this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);
1639
1826
  } catch (error) {
1640
- (0, logger_exports.Logger)("An error occurred while fetching remote chunks.", logger_exports.LOG_LEVEL_VERBOSE);
1641
- (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
+ }
1642
1843
  } finally {
1643
1844
  for (const [id, pending] of requestClaims) {
1644
1845
  if (pending.inFlight) this.settleClaim(id, pending);
@@ -1656,6 +1857,14 @@ import { FallbackWeakRef as FallbackWeakRef3 } from "octagonal-wheels/common/pol
1656
1857
  // lib/livesync-commonlib/src/common/utils.ts
1657
1858
  import { LRUCache } from "octagonal-wheels/memory/LRUCache";
1658
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
+
1659
1868
  // lib/livesync-commonlib/src/string_and_binary/path.ts
1660
1869
  import { Minimatch } from "minimatch";
1661
1870
  import { unique as unique2 } from "octagonal-wheels/collection.js";
@@ -1674,12 +1883,8 @@ function addPrefix(path, prefix) {
1674
1883
  return `${prefix ?? ""}${path}`;
1675
1884
  }
1676
1885
  function expandFilePathPrefix(path) {
1677
- for (const prefix of [ICHeader, ICXHeader, PSCHeader]) {
1678
- if (path.startsWith(prefix)) {
1679
- return [prefix, path.substring(prefix.length)];
1680
- }
1681
- }
1682
- return ["", path];
1886
+ const [prefix, body] = splitPathNamespace(path);
1887
+ return [prefix, body];
1683
1888
  }
1684
1889
  function expandDocumentIDPrefix(id) {
1685
1890
  for (const prefix of [CHeader, PREFIX_OBFUSCATED]) {
@@ -1754,8 +1959,10 @@ function shouldSplitAsPlainText(filename) {
1754
1959
 
1755
1960
  // lib/livesync-commonlib/src/common/utils.ts
1756
1961
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
1757
- 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";
1758
1964
  import { concatUInt8Array } from "octagonal-wheels/binary";
1965
+ import { createBinaryBlob, createTextBlob, isBlobContentEqual, toBlob } from "octagonal-wheels/binary/blob";
1759
1966
  import { delay as delay2, fireAndForget } from "octagonal-wheels/promises";
1760
1967
  import { arrayToChunkedArray, unique as unique3 } from "octagonal-wheels/collection";
1761
1968
  import { extractObject, isObjectDifferent } from "octagonal-wheels/object";
@@ -1872,8 +2079,9 @@ var LiveSyncError = class _LiveSyncError extends Error {
1872
2079
  };
1873
2080
 
1874
2081
  // lib/livesync-commonlib/src/common/utils.object.ts
2082
+ import { cloneViaJSON } from "octagonal-wheels/encoding/json";
1875
2083
  function asCopy(obj) {
1876
- return JSON.parse(JSON.stringify(obj));
2084
+ return cloneViaJSON(obj);
1877
2085
  }
1878
2086
 
1879
2087
  // lib/livesync-commonlib/src/common/utils.patch.ts
@@ -1881,6 +2089,17 @@ var MARK_OPERATOR = ``;
1881
2089
  var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;
1882
2090
  var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;
1883
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
+ }
1884
2103
  function unorderedArrayToObject(obj) {
1885
2104
  return obj.map((e) => ({ [e.id]: e })).reduce((p, c) => ({ ...p, ...c }), {});
1886
2105
  }
@@ -1909,34 +2128,34 @@ function generatePatchObj(from, to) {
1909
2128
  const newEntries = Object.entries(to);
1910
2129
  for (const [key, value] of newEntries) {
1911
2130
  if (!tempMap.has(key)) {
1912
- ret[key] = value;
2131
+ setOwnProperty(ret, key, value);
1913
2132
  tempMap.delete(key);
1914
2133
  } else {
1915
2134
  const v = tempMap.get(key);
1916
2135
  if (typeof v !== typeof value || Array.isArray(v) !== Array.isArray(value)) {
1917
- ret[key] = { [MARK_SWAPPED]: value };
2136
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1918
2137
  } else {
1919
2138
  if (v === null && value === null) {
1920
2139
  } else if (v === null && value !== null) {
1921
- ret[key] = { [MARK_SWAPPED]: value };
2140
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1922
2141
  } else if (v !== null && value === null) {
1923
- ret[key] = { [MARK_SWAPPED]: value };
2142
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1924
2143
  } else if (typeof v == "object" && typeof value == "object" && !Array.isArray(v) && !Array.isArray(value)) {
1925
2144
  const wk = generatePatchObj(
1926
2145
  v,
1927
2146
  value
1928
2147
  );
1929
- if (Object.keys(wk).length > 0) ret[key] = wk;
2148
+ if (Object.keys(wk).length > 0) setOwnProperty(ret, key, wk);
1930
2149
  } else if (typeof v == "object" && typeof value == "object" && Array.isArray(v) && Array.isArray(value)) {
1931
2150
  const wk = generatePatchUnorderedArray(v, value);
1932
- if (Object.keys(wk).length > 0) ret[key] = wk;
2151
+ if (Object.keys(wk).length > 0) setOwnProperty(ret, key, wk);
1933
2152
  } else if (typeof v != "object" && typeof value != "object") {
1934
2153
  if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
1935
- ret[key] = value;
2154
+ setOwnProperty(ret, key, value);
1936
2155
  }
1937
2156
  } else {
1938
2157
  if (JSON.stringify(tempMap.get(key)) !== JSON.stringify(value)) {
1939
- ret[key] = { [MARK_SWAPPED]: value };
2158
+ setOwnProperty(ret, key, { [MARK_SWAPPED]: value });
1940
2159
  }
1941
2160
  }
1942
2161
  }
@@ -1944,7 +2163,7 @@ function generatePatchObj(from, to) {
1944
2163
  }
1945
2164
  }
1946
2165
  for (const [key] of tempMap) {
1947
- ret[key] = MARK_DELETED;
2166
+ setOwnProperty(ret, key, MARK_DELETED);
1948
2167
  }
1949
2168
  return ret;
1950
2169
  }
@@ -1952,21 +2171,21 @@ function applyPatch(from, patch) {
1952
2171
  const ret = from;
1953
2172
  const patches = Object.entries(patch);
1954
2173
  for (const [key, value] of patches) {
1955
- if (value == MARK_DELETED) {
2174
+ if (value === MARK_DELETED) {
1956
2175
  delete ret[key];
1957
2176
  continue;
1958
2177
  }
1959
2178
  if (value === null) {
1960
- ret[key] = null;
2179
+ setOwnProperty(ret, key, null);
1961
2180
  continue;
1962
2181
  }
1963
2182
  if (typeof value == "object") {
1964
- if (MARK_SWAPPED in value) {
1965
- ret[key] = value[MARK_SWAPPED];
2183
+ if (hasOwnProperty(value, MARK_SWAPPED)) {
2184
+ setOwnProperty(ret, key, value[MARK_SWAPPED]);
1966
2185
  continue;
1967
2186
  }
1968
- if (MARK_ISARRAY in value) {
1969
- if (!(key in ret)) ret[key] = [];
2187
+ if (hasOwnProperty(value, MARK_ISARRAY)) {
2188
+ if (!hasOwnProperty(ret, key)) setOwnProperty(ret, key, []);
1970
2189
  if (!Array.isArray(ret[key])) {
1971
2190
  throw new Error("Patch target type is mismatched (array to something)");
1972
2191
  }
@@ -1976,19 +2195,23 @@ function applyPatch(from, patch) {
1976
2195
  value[MARK_ISARRAY]
1977
2196
  );
1978
2197
  const appliedArray = objectToUnorderedArray(appliedObject);
1979
- ret[key] = [...appliedArray];
2198
+ setOwnProperty(ret, key, [...appliedArray]);
1980
2199
  } else {
1981
- if (!(key in ret)) {
1982
- ret[key] = value;
2200
+ if (!hasOwnProperty(ret, key)) {
2201
+ setOwnProperty(ret, key, value);
1983
2202
  continue;
1984
2203
  }
1985
- ret[key] = applyPatch(
1986
- ret[key],
1987
- value
2204
+ setOwnProperty(
2205
+ ret,
2206
+ key,
2207
+ applyPatch(
2208
+ ret[key],
2209
+ value
2210
+ )
1988
2211
  );
1989
2212
  }
1990
2213
  } else {
1991
- ret[key] = value;
2214
+ setOwnProperty(ret, key, value);
1992
2215
  }
1993
2216
  }
1994
2217
  return ret;
@@ -2022,17 +2245,8 @@ function getDocData(doc) {
2022
2245
  function isTextBlob(blob) {
2023
2246
  return blob.type === "text/plain";
2024
2247
  }
2025
- function createTextBlob(data) {
2026
- const d = Array.isArray(data) ? data : [data];
2027
- return new Blob(d, { endings: "transparent", type: "text/plain" });
2028
- }
2029
- function createBinaryBlob(data) {
2030
- return new Blob([data], { endings: "transparent", type: "application/octet-stream" });
2031
- }
2032
2248
  function createBlob(data) {
2033
- if (data instanceof Blob) return data;
2034
- if (data instanceof Uint8Array || data instanceof ArrayBuffer) return createBinaryBlob(data);
2035
- return createTextBlob(data);
2249
+ return toBlob(data);
2036
2250
  }
2037
2251
  function isTextDocument(doc) {
2038
2252
  if (doc.type == "plain") return true;
@@ -2049,13 +2263,13 @@ function readContent(doc) {
2049
2263
  }
2050
2264
  var isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== "undefined";
2051
2265
  function isObfuscatedEntry(doc) {
2052
- if (doc._id.startsWith(PREFIX_OBFUSCATED)) {
2266
+ if (doc._id.startsWith(IDPrefixes.Obfuscated)) {
2053
2267
  return true;
2054
2268
  }
2055
2269
  return false;
2056
2270
  }
2057
2271
  function isEncryptedChunkEntry(doc) {
2058
- if (doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) {
2272
+ if (doc._id.startsWith(IDPrefixes.EncryptedChunk)) {
2059
2273
  return true;
2060
2274
  }
2061
2275
  return false;
@@ -2613,14 +2827,16 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
2613
2827
  }
2614
2828
  }
2615
2829
  const chunkUnitBinary = 256 * 1024;
2616
- const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4;
2617
2830
  const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16;
2618
- const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary;
2619
2831
  const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;
2620
2832
  const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);
2621
2833
  const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);
2622
- const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);
2623
- 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;
2624
2840
  const windowSize = 48;
2625
2841
  const hashModulus = avgChunkSize;
2626
2842
  const boundaryPattern = 1;
@@ -2638,7 +2854,7 @@ async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit,
2638
2854
  return async function* piecesBlob() {
2639
2855
  while (pos < length) {
2640
2856
  const byte = buffer[pos];
2641
- if (pos >= start + windowSize) {
2857
+ if (pos >= windowSize) {
2642
2858
  const oldByte = buffer[pos - windowSize];
2643
2859
  const oldByteTerm = Math.imul(oldByte, P_pow_w);
2644
2860
  hash = hash - oldByteTerm | 0;
@@ -2729,23 +2945,8 @@ var ContentSplitterRabinKarp = class extends ContentSplitterBase {
2729
2945
  return settings.chunkSplitterVersion === ChunkAlgorithms.RabinKarp;
2730
2946
  }
2731
2947
  async processSplit(options) {
2732
- if (options.useWorker) {
2733
- return (await splitPieces2WorkerRabinKarp(
2734
- options.blob,
2735
- options.pieceSize,
2736
- options.plainSplit,
2737
- options.minimumChunkSize,
2738
- options.path
2739
- ))();
2740
- } else {
2741
- return (await splitPiecesRabinKarp(
2742
- options.blob,
2743
- options.pieceSize,
2744
- options.plainSplit,
2745
- options.minimumChunkSize,
2746
- options.path
2747
- ))();
2748
- }
2948
+ const split = options.useWorker ? splitPieces2WorkerRabinKarp : splitPiecesRabinKarp;
2949
+ return (await split(options.blob, options.pieceSize, options.plainSplit, options.minimumChunkSize, options.path))();
2749
2950
  }
2750
2951
  };
2751
2952
 
@@ -2756,25 +2957,15 @@ var ContentSplitterV1 = class extends ContentSplitterBase {
2756
2957
  return settings.chunkSplitterVersion === ChunkAlgorithms.V1 || settings.chunkSplitterVersion === "" || settings.chunkSplitterVersion === void 0;
2757
2958
  }
2758
2959
  async processSplit(options) {
2759
- if (options.useWorker) {
2760
- return (await splitPieces2Worker(
2761
- options.blob,
2762
- options.pieceSize,
2763
- options.plainSplit,
2764
- options.minimumChunkSize,
2765
- options.path,
2766
- options.useSegmenter
2767
- ))();
2768
- } else {
2769
- return (await splitPieces2(
2770
- options.blob,
2771
- options.pieceSize,
2772
- options.plainSplit,
2773
- options.minimumChunkSize,
2774
- options.path,
2775
- options.useSegmenter
2776
- ))();
2777
- }
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
+ ))();
2778
2969
  }
2779
2970
  };
2780
2971
 
@@ -2785,25 +2976,15 @@ var ContentSplitterV2 = class extends ContentSplitterBase {
2785
2976
  return settings.chunkSplitterVersion === ChunkAlgorithms.V2 || settings.chunkSplitterVersion === ChunkAlgorithms.V2Segmenter;
2786
2977
  }
2787
2978
  async processSplit(options) {
2788
- if (options.useWorker) {
2789
- return (await splitPieces2WorkerV2(
2790
- options.blob,
2791
- options.pieceSize,
2792
- options.plainSplit,
2793
- options.minimumChunkSize,
2794
- options.path,
2795
- options.useSegmenter
2796
- ))();
2797
- } else {
2798
- return (await splitPieces2V2(
2799
- options.blob,
2800
- options.pieceSize,
2801
- options.plainSplit,
2802
- options.minimumChunkSize,
2803
- options.path,
2804
- options.useSegmenter
2805
- ))();
2806
- }
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
+ ))();
2807
2988
  }
2808
2989
  };
2809
2990
 
@@ -3894,7 +4075,7 @@ var ConflictManager = class {
3894
4075
  };
3895
4076
 
3896
4077
  // lib/livesync-commonlib/src/managers/EntryManager/EntryManagerImpls.ts
3897
- 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";
3898
4079
  import { serialized } from "octagonal-wheels/concurrency/lock";
3899
4080
  async function createChunks(managers, dispFilename, note) {
3900
4081
  const { chunkManager, splitter } = managers;
@@ -3927,7 +4108,7 @@ async function createChunks(managers, dispFilename, note) {
3927
4108
  note._id
3928
4109
  );
3929
4110
  if (result.result === false) {
3930
- Logger9(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
4111
+ Logger9(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE4);
3931
4112
  return false;
3932
4113
  }
3933
4114
  totalWritingCount++;
@@ -3941,7 +4122,7 @@ async function createChunks(managers, dispFilename, note) {
3941
4122
  const flushIfNeeded = async () => {
3942
4123
  if (bufferedSize > MAX_WRITE_SIZE) {
3943
4124
  if (!await flushBufferedChunks()) {
3944
- Logger9(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE3);
4125
+ Logger9(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE4);
3945
4126
  return false;
3946
4127
  }
3947
4128
  }
@@ -3991,7 +4172,7 @@ async function createChunks(managers, dispFilename, note) {
3991
4172
  if (dataSize > 0 && totalWritingCount === 0) {
3992
4173
  Logger9(
3993
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!`,
3994
- LOG_LEVEL_NOTICE3
4175
+ LOG_LEVEL_NOTICE4
3995
4176
  );
3996
4177
  }
3997
4178
  return chunks;
@@ -4048,7 +4229,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4048
4229
  path: note.path,
4049
4230
  ctime: note.ctime,
4050
4231
  mtime: note.mtime,
4051
- size: note.size,
4232
+ size: data.size,
4052
4233
  type: note.datatype,
4053
4234
  eden: {}
4054
4235
  };
@@ -4084,7 +4265,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4084
4265
  }) ?? false;
4085
4266
  });
4086
4267
  if (result === false) {
4087
- Logger9(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE3);
4268
+ Logger9(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE4);
4088
4269
  return false;
4089
4270
  }
4090
4271
  Logger9(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE9);
@@ -4092,7 +4273,8 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
4092
4273
  }
4093
4274
  function isTargetFile(host, filenameSrc) {
4094
4275
  const settings = host.services.setting.currentSettings();
4095
- 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;
4096
4278
  if (file.startsWith(ICXHeader)) return true;
4097
4279
  if (file.startsWith(PSCHeader)) return true;
4098
4280
  if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) {
@@ -4103,7 +4285,7 @@ function isTargetFile(host, filenameSrc) {
4103
4285
  return false;
4104
4286
  }
4105
4287
  }
4106
- if (settings.syncOnlyRegEx) {
4288
+ if (!isInternalFile && settings.syncOnlyRegEx) {
4107
4289
  const syncOnly = getFileRegExp(settings, "syncOnlyRegEx");
4108
4290
  if (syncOnly.length > 0 && !syncOnly.some((e) => e.test(file))) return false;
4109
4291
  }
@@ -4133,12 +4315,29 @@ async function getDBEntryMetaByPath(host, { localDatabase }, path, opt, includeD
4133
4315
  const id = await host.services.path.path2id(path);
4134
4316
  try {
4135
4317
  let obj = null;
4136
- if (opt) {
4137
- obj = await localDatabase.get(id, opt);
4138
- } else {
4139
- 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;
4140
4339
  }
4141
- const deleted = obj?.deleted ?? obj._deleted ?? void 0;
4340
+ const deleted = obj._deleted || obj.deleted;
4142
4341
  if (!includeDeleted && deleted) return false;
4143
4342
  if (obj.type && obj.type == "leaf") {
4144
4343
  return false;
@@ -4320,13 +4519,13 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
4320
4519
  if (isErrorOfMissingDoc(ex)) {
4321
4520
  Logger9(
4322
4521
  `Missing document content!, could not read ${dispFilename}(${meta._id.substring(0, 8)}) from database.`,
4323
- LOG_LEVEL_NOTICE3
4522
+ LOG_LEVEL_NOTICE4
4324
4523
  );
4325
4524
  return false;
4326
4525
  }
4327
4526
  Logger9(
4328
4527
  `Something went wrong on reading ${dispFilename}(${meta._id.substring(0, 8)}) from database:`,
4329
- LOG_LEVEL_NOTICE3
4528
+ LOG_LEVEL_NOTICE4
4330
4529
  );
4331
4530
  Logger9(ex);
4332
4531
  }
@@ -4494,21 +4693,29 @@ var EntryManager = class {
4494
4693
  return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);
4495
4694
  }
4496
4695
  async deleteDBEntry(path, opt) {
4696
+ await this.checkPathIdentity();
4497
4697
  return await deleteDBEntryByPath(this.serviceHost, this, path, opt);
4498
4698
  }
4499
4699
  async storeDeletionAtRevision(path, baseRevision) {
4700
+ await this.checkPathIdentity();
4500
4701
  return await storeDeletionByPathAtRevision(this.serviceHost, this, path, baseRevision);
4501
4702
  }
4502
4703
  async putDBEntry(note, onlyChunks, conflictBaseRev) {
4704
+ await this.checkPathIdentity();
4503
4705
  return await putDBEntry(this.serviceHost, this, note, onlyChunks, conflictBaseRev);
4504
4706
  }
4505
4707
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
4708
+ await this.checkPathIdentity();
4506
4709
  return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);
4507
4710
  }
4508
4711
  /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */
4509
4712
  async putDBEntryAsIndependentRoot(note) {
4713
+ await this.checkPathIdentity();
4510
4714
  return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);
4511
4715
  }
4716
+ async checkPathIdentity() {
4717
+ await assertDatabasePathIdentity(this.localDatabase, this.options.settingService.currentSettings(), true);
4718
+ }
4512
4719
  };
4513
4720
 
4514
4721
  // lib/livesync-commonlib/src/managers/HashManager/HashManagerCore.ts
@@ -4916,7 +5123,7 @@ var HashManager = class extends HashManagerCore {
4916
5123
  // lib/livesync-commonlib/src/services/lib/logUtils.ts
4917
5124
  import {
4918
5125
  LOG_LEVEL_INFO as LOG_LEVEL_INFO4,
4919
- LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE4,
5126
+ LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE5,
4920
5127
  LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE11,
4921
5128
  Logger as Logger11
4922
5129
  } from "octagonal-wheels/common/logger";
@@ -4931,7 +5138,7 @@ function createInstanceLogFunction(serviceName, APIService2) {
4931
5138
  return;
4932
5139
  }
4933
5140
  let formattedMsg = typeof msg === "string" ? msg : isError ? msg.message : JSON.stringify(msg);
4934
- if (level < LOG_LEVEL_NOTICE4) {
5141
+ if (level < LOG_LEVEL_NOTICE5) {
4935
5142
  formattedMsg = `[${serviceName}]${MARK_LOG_SEPARATOR} ${formattedMsg}`;
4936
5143
  }
4937
5144
  logFunc(formattedMsg, level, key);
@@ -5008,6 +5215,7 @@ var LiveSyncManagers = class {
5008
5215
  });
5009
5216
  const chunkFetcher = new ChunkFetcher({
5010
5217
  chunkManager,
5218
+ source: this.options.chunkFetchSource,
5011
5219
  replicatorService: this.options.replicatorService,
5012
5220
  settingService: this.options.settingService
5013
5221
  });
@@ -5077,6 +5285,17 @@ function getNoFromRev(rev) {
5077
5285
  return parseInt(rev.split("-")[0]);
5078
5286
  }
5079
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
+ }
5080
5299
  auth;
5081
5300
  dbname;
5082
5301
  settings;
@@ -5108,16 +5327,6 @@ var LiveSyncLocalDB = class {
5108
5327
  /** Share owner retirement across every close path for one physical database lifetime. */
5109
5328
  activeReplicationClose;
5110
5329
  databaseUnloadNotification;
5111
- constructor(dbname, env) {
5112
- this.auth = {
5113
- username: "",
5114
- password: ""
5115
- };
5116
- this.dbname = dbname;
5117
- this.env = env;
5118
- this._log = createInstanceLogFunction("LiveSyncLocalDB", this.env.services.API);
5119
- this.refreshSettings();
5120
- }
5121
5330
  /** Notify dependent services at most once for each physical database lifecycle. */
5122
5331
  notifyDatabaseUnload() {
5123
5332
  if (!this.databaseUnloadNotification) {
@@ -5231,6 +5440,7 @@ var LiveSyncLocalDB = class {
5231
5440
  this.databaseUnloadNotification = void 0;
5232
5441
  const manager = new LiveSyncManagers({
5233
5442
  database: this.localDatabase,
5443
+ chunkFetchSource: this.runtimeOptions?.createChunkFetchSource?.(this.localDatabase),
5234
5444
  APIService: this.env.services.API,
5235
5445
  pathService: this.env.services.path,
5236
5446
  replicatorService: this.env.services.replicator,
@@ -5246,6 +5456,7 @@ var LiveSyncLocalDB = class {
5246
5456
  this._log("Database initialisation was rejected by a required module.", LOG_LEVEL_NOTICE);
5247
5457
  return false;
5248
5458
  }
5459
+ manager.changeManager.restartWatch();
5249
5460
  this._log("Opening Database...");
5250
5461
  this._log("Database info", LOG_LEVEL_VERBOSE);
5251
5462
  this._log(JSON.stringify(await openedDatabase.info(), null, 2), LOG_LEVEL_VERBOSE);
@@ -5634,13 +5845,155 @@ var MARK_SHIFT = `L`;
5634
5845
  var MARK_SHIFT_COMPRESSED = `${MARK_SHIFT}Z`;
5635
5846
 
5636
5847
  // lib/livesync-commonlib/src/pouchdb/encryption.ts
5637
- 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
5638
5991
  var encrypt2 = encryptWorker;
5639
5992
  var decrypt2 = decryptWorker;
5640
5993
  var encryptHKDF2 = encryptHKDFWorker;
5641
5994
  var decryptHKDF2 = decryptHKDFWorker;
5642
5995
  var Encrypt_HKDF_Header = "%=";
5643
- var Encrypt_OLD_Header = "%";
5996
+ var Encrypt_OLD_Header = ENCRYPT_V2_PREFIX2;
5644
5997
  var EncryptionVersions = {
5645
5998
  UNENCRYPTED: 0,
5646
5999
  ENCRYPTED: 1,
@@ -5658,20 +6011,17 @@ function getEncryptionVersion(data) {
5658
6011
  }
5659
6012
  return EncryptionVersions.UNENCRYPTED;
5660
6013
  }
5661
- async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicIterationCount) {
6014
+ async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicIterationCount, log = logger_exports.Logger) {
5662
6015
  try {
5663
6016
  return await decrypt2(encryptedData, passphrase, useDynamicIterationCount);
5664
6017
  } catch (ex) {
5665
6018
  try {
5666
- (0, logger_exports.Logger)(
5667
- "Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",
5668
- logger_exports.LOG_LEVEL_VERBOSE
5669
- );
5670
- (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);
5671
6021
  return await decrypt2(encryptedData, passphrase, false);
5672
6022
  } catch (ex2) {
5673
- (0, logger_exports.Logger)("Completely failed to decrypt with V1 method.", logger_exports.LOG_LEVEL_VERBOSE);
5674
- (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);
5675
6025
  return false;
5676
6026
  }
5677
6027
  }
@@ -5681,9 +6031,7 @@ function isEncryptedMeta(doc) {
5681
6031
  return "path" in doc && doc.path.startsWith(ENCRYPTED_META_PREFIX);
5682
6032
  }
5683
6033
  function isInternalObfuscatedEntry(doc) {
5684
- return [ICHeader, ICXHeader, PSCHeader].some(
5685
- (prefix) => doc._id.startsWith(`${prefix}${PREFIX_OBFUSCATED}`)
5686
- );
6034
+ return [ICHeader, ICXHeader, PSCHeader].some((prefix) => doc._id.startsWith(`${prefix}${IDPrefixes.Obfuscated}`));
5687
6035
  }
5688
6036
  async function encryptMetaWithHKDF(doc, passphrase, pbkdf2Salt) {
5689
6037
  if (isEncryptedMeta(doc)) {
@@ -5779,10 +6127,11 @@ async function incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, ge
5779
6127
  }
5780
6128
  return saveDoc;
5781
6129
  }
5782
- async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt) {
6130
+ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt, log, algorithm, acceptUnencryptedContent) {
5783
6131
  const loadDoc = {
5784
6132
  ...doc
5785
6133
  };
6134
+ assertUnencryptedContentPolicy(loadDoc, algorithm, acceptUnencryptedContent);
5786
6135
  if (isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc)) {
5787
6136
  try {
5788
6137
  const encryptionVersion = getEncryptionVersion(loadDoc);
@@ -5791,21 +6140,26 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5791
6140
  loadDoc.data = await decryptHKDF2(loadDoc.data, passphrase, pbkdf2salt);
5792
6141
  delete loadDoc.e_;
5793
6142
  } else if (encryptionVersion === EncryptionVersions.ENCRYPTED) {
5794
- const decryptedData = await tryDecryptV1AsFallback(loadDoc.data, passphrase, useDynamicIterationCount);
6143
+ const decryptedData = await tryDecryptV1AsFallback(
6144
+ loadDoc.data,
6145
+ passphrase,
6146
+ useDynamicIterationCount,
6147
+ log
6148
+ );
5795
6149
  if (decryptedData === false) {
5796
- (0, logger_exports.Logger)(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
6150
+ log(MESSAGE_FALLBACK_DECRYPT_FAILED, logger_exports.LOG_LEVEL_NOTICE);
5797
6151
  throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5798
6152
  }
5799
6153
  loadDoc.data = decryptedData;
5800
6154
  delete loadDoc.e_;
5801
6155
  } else if (encryptionVersion === EncryptionVersions.UNENCRYPTED) {
5802
6156
  } else {
5803
- (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);
5804
6158
  throw new Error("Unknown encryption version. Cannot decrypt.");
5805
6159
  }
5806
6160
  } catch (ex) {
5807
- (0, logger_exports.Logger)(DECRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
5808
- (0, logger_exports.Logger)(ex);
6161
+ log(DECRYPTION_HKDF_FAILED, logger_exports.LOG_LEVEL_NOTICE);
6162
+ log(ex);
5809
6163
  throw ex;
5810
6164
  }
5811
6165
  }
@@ -5818,16 +6172,16 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5818
6172
  loadDoc[key] = metadata[key];
5819
6173
  }
5820
6174
  } catch (ex) {
5821
- (0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
5822
- (0, logger_exports.Logger)(ex);
6175
+ log(`${DECRYPTION_HKDF_FAILED} on Path`, logger_exports.LOG_LEVEL_NOTICE);
6176
+ log(ex);
5823
6177
  throw ex;
5824
6178
  }
5825
6179
  } else {
5826
6180
  const path = getPath(loadDoc);
5827
6181
  if (isPathProbablyObfuscated(path)) {
5828
- const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
6182
+ const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount, log);
5829
6183
  if (decryptedPath === false) {
5830
- (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);
5831
6185
  throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5832
6186
  }
5833
6187
  loadDoc.path = decryptedPath;
@@ -5841,7 +6195,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5841
6195
  const decryptedEden = await tryDecryptV1AsFallback(
5842
6196
  loadDoc.eden[EDEN_ENCRYPTED_KEY].data,
5843
6197
  passphrase,
5844
- useDynamicIterationCount
6198
+ useDynamicIterationCount,
6199
+ log
5845
6200
  );
5846
6201
  if (decryptedEden === false) throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
5847
6202
  readEden = {
@@ -5850,8 +6205,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5850
6205
  };
5851
6206
  edenDecrypted = true;
5852
6207
  } catch (ex) {
5853
- (0, logger_exports.Logger)(`${DECRYPTION_FALLBACK_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
5854
- (0, logger_exports.Logger)(ex);
6208
+ log(`${DECRYPTION_FALLBACK_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
6209
+ log(ex);
5855
6210
  throw ex;
5856
6211
  }
5857
6212
  }
@@ -5869,8 +6224,8 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
5869
6224
  };
5870
6225
  edenDecrypted = true;
5871
6226
  } catch (ex) {
5872
- (0, logger_exports.Logger)(`${DECRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
5873
- (0, logger_exports.Logger)(ex);
6227
+ log(`${DECRYPTION_HKDF_FAILED} on Eden`, logger_exports.LOG_LEVEL_NOTICE);
6228
+ log(ex);
5874
6229
  throw ex;
5875
6230
  }
5876
6231
  }
@@ -5922,28 +6277,30 @@ async function incomingEncryptV1(doc, passphrase, useDynamicIterationCount) {
5922
6277
  }
5923
6278
  return saveDoc;
5924
6279
  }
5925
- async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount) {
6280
+ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, log, acceptUnencryptedContent) {
5926
6281
  const loadDoc = {
5927
6282
  ...doc
5928
6283
  };
5929
6284
  const _isChunkOrSyncInfo = isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc);
5930
6285
  const _isObfuscatedEntry = isObfuscatedEntry(loadDoc);
5931
6286
  const _shouldDecryptEden = shouldDecryptEden(loadDoc);
5932
- 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) {
5933
6297
  if (migrationDecrypt && decrypted.has(loadDoc._id)) {
5934
6298
  return loadDoc;
5935
6299
  }
5936
6300
  try {
5937
- if (_isChunkOrSyncInfo) {
6301
+ if (_shouldDecryptData) {
5938
6302
  loadDoc.data = await decrypt2(loadDoc.data, passphrase, useDynamicIterationCount);
5939
- delete loadDoc.e_;
5940
- } else if ("e_" in loadDoc) {
5941
- loadDoc.data = await decrypt2(
5942
- loadDoc.data,
5943
- passphrase,
5944
- useDynamicIterationCount
5945
- );
5946
- delete loadDoc.e_;
6303
+ if ("e_" in loadDoc) delete loadDoc.e_;
5947
6304
  }
5948
6305
  if (_isObfuscatedEntry) {
5949
6306
  const path = getPath(loadDoc);
@@ -5966,7 +6323,7 @@ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, u
5966
6323
  } catch (ex) {
5967
6324
  if (useDynamicIterationCount) {
5968
6325
  try {
5969
- if (_isChunkOrSyncInfo) {
6326
+ if (_shouldDecryptData) {
5970
6327
  loadDoc.data = await decrypt2(loadDoc.data, passphrase, false);
5971
6328
  }
5972
6329
  if (_isObfuscatedEntry) {
@@ -5987,15 +6344,15 @@ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, u
5987
6344
  if (migrationDecrypt && ex2 instanceof SyntaxError) {
5988
6345
  return loadDoc;
5989
6346
  }
5990
- (0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
5991
- (0, logger_exports.Logger)(ex2, logger_exports.LOG_LEVEL_VERBOSE);
5992
- (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);
5993
6350
  throw ex2;
5994
6351
  }
5995
6352
  } else {
5996
- (0, logger_exports.Logger)("Decryption failed.", logger_exports.LOG_LEVEL_NOTICE);
5997
- (0, logger_exports.Logger)(ex, logger_exports.LOG_LEVEL_VERBOSE);
5998
- (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);
5999
6356
  throw ex;
6000
6357
  }
6001
6358
  }
@@ -6008,8 +6365,9 @@ var preprocessOutgoing = async (doc) => {
6008
6365
  var preprocessIncoming = async (doc) => {
6009
6366
  return await Promise.resolve(doc);
6010
6367
  };
6011
- 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) {
6012
6369
  const decryptedCache = /* @__PURE__ */ new Map();
6370
+ const acceptUnencrypted = normaliseAcceptUnencryptedContent(acceptUnencryptedContent);
6013
6371
  const incoming = (doc) => algorithm === E2EEAlgorithms.V2 ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt, encryptInternalMetadata) : incomingEncryptV1(doc, passphrase, useDynamicIterationCount);
6014
6372
  const outgoing = (doc) => algorithm !== E2EEAlgorithms.ForceV1 ? outgoingDecryptHKDF(
6015
6373
  doc,
@@ -6017,21 +6375,34 @@ function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCoun
6017
6375
  decryptedCache,
6018
6376
  passphrase,
6019
6377
  useDynamicIterationCount,
6020
- getPBKDF2Salt
6021
- ) : 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
+ );
6022
6391
  return {
6023
6392
  incoming,
6024
6393
  outgoing
6025
6394
  };
6026
6395
  }
6027
- var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false) => {
6396
+ var enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, acceptUnencryptedContent = false) => {
6028
6397
  const { incoming, outgoing } = getConfiguredFunctionsForEncryption(
6029
6398
  passphrase,
6030
6399
  useDynamicIterationCount,
6031
6400
  migrationDecrypt,
6032
6401
  getPBKDF2Salt,
6033
6402
  algorithm,
6034
- encryptInternalMetadata
6403
+ encryptInternalMetadata,
6404
+ logger_exports.Logger,
6405
+ acceptUnencryptedContent
6035
6406
  );
6036
6407
  db.transform({
6037
6408
  incoming,
@@ -6046,44 +6417,15 @@ function disableEncryption() {
6046
6417
  return await Promise.resolve(doc);
6047
6418
  };
6048
6419
  }
6049
- var EDEN_ENCRYPTED_KEY = "h:++encrypted";
6050
- var EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
6051
- function shouldEncryptEden(doc) {
6052
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
6053
- return true;
6054
- }
6055
- return false;
6056
- }
6057
- function shouldEncryptEdenHKDF(doc) {
6058
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
6059
- if (Object.keys(doc.eden).length === 0) {
6060
- return false;
6061
- }
6062
- return true;
6063
- }
6064
- return false;
6065
- }
6066
- function shouldDecryptEden(doc) {
6067
- if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
6068
- return true;
6069
- }
6070
- return false;
6071
- }
6072
- function shouldDecryptEdenHKDF(doc) {
6073
- if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
6074
- return true;
6075
- }
6076
- return false;
6077
- }
6078
6420
 
6079
6421
  // lib/livesync-commonlib/src/API/DirectFileManipulatorV2.ts
6080
6422
  import {
6081
- LEVEL_INFO as LEVEL_INFO2,
6082
- LEVEL_VERBOSE,
6423
+ LEVEL_INFO as LEVEL_INFO3,
6424
+ LEVEL_VERBOSE as LEVEL_VERBOSE2,
6083
6425
  LOG_LEVEL_INFO as LOG_LEVEL_INFO6,
6084
- LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE9,
6426
+ LOG_LEVEL_NOTICE as LOG_LEVEL_NOTICE10,
6085
6427
  LOG_LEVEL_VERBOSE as LOG_LEVEL_VERBOSE21,
6086
- Logger as Logger19
6428
+ Logger as Logger20
6087
6429
  } from "octagonal-wheels/common/logger";
6088
6430
  import { promiseWithResolvers as promiseWithResolvers8 } from "octagonal-wheels/promises";
6089
6431
 
@@ -6220,6 +6562,7 @@ var Binder = class {
6220
6562
  }
6221
6563
  }
6222
6564
  _callback = null;
6565
+ _registrationToken = null;
6223
6566
  /**
6224
6567
  * Assigns a new handler function.
6225
6568
  * @param callback The new handler function to assign.
@@ -6228,8 +6571,14 @@ var Binder = class {
6228
6571
  if (this._callback && !override) {
6229
6572
  throw new Error(`Handler ${this._name} is already assigned.`);
6230
6573
  }
6574
+ const registrationToken = /* @__PURE__ */ Symbol();
6575
+ this._registrationToken = registrationToken;
6231
6576
  this._callback = callback;
6232
6577
  return () => {
6578
+ if (this._registrationToken !== registrationToken) {
6579
+ return;
6580
+ }
6581
+ this._registrationToken = null;
6233
6582
  this._callback = null;
6234
6583
  };
6235
6584
  }
@@ -6249,6 +6598,7 @@ var LazyBinder = class {
6249
6598
  _name;
6250
6599
  _callbackPromise = promiseWithResolvers6();
6251
6600
  _callback = null;
6601
+ _registrationToken = null;
6252
6602
  /**
6253
6603
  * Creates a new LazyBinder instance.
6254
6604
  * @param name The name of the handler.
@@ -6265,9 +6615,15 @@ var LazyBinder = class {
6265
6615
  if (this._callback && !override) {
6266
6616
  throw new Error(`Handler ${this._name} is already assigned.`);
6267
6617
  }
6618
+ const registrationToken = /* @__PURE__ */ Symbol();
6619
+ this._registrationToken = registrationToken;
6268
6620
  this._callback = callback;
6269
6621
  this._callbackPromise.resolve();
6270
6622
  return () => {
6623
+ if (this._registrationToken !== registrationToken) {
6624
+ return;
6625
+ }
6626
+ this._registrationToken = null;
6271
6627
  this._callback = null;
6272
6628
  this._callbackPromise = promiseWithResolvers6();
6273
6629
  };
@@ -6511,6 +6867,30 @@ var FirstResultHandler = class extends MultiBinder {
6511
6867
  return false;
6512
6868
  }
6513
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
+ };
6514
6894
  function getMultipleBound(handler) {
6515
6895
  const _handler = "invoke" in handler ? handler.invoke : handler.dispatch;
6516
6896
  const __handler = _handler.bind(handler);
@@ -6552,6 +6932,17 @@ function firstResultFunction(name) {
6552
6932
  const handler = new FirstResultHandler(name ?? "firstResultFunction");
6553
6933
  return getMultipleBound(handler);
6554
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
+ }
6555
6946
  function dispatchParallelFunction(name) {
6556
6947
  const handler = new DispatchParallel(
6557
6948
  name ?? "dispatchParallelFunction"
@@ -6637,6 +7028,15 @@ function handlers() {
6637
7028
  firstResult(name) {
6638
7029
  return firstResultFunction(String(name));
6639
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
+ },
6640
7040
  /**
6641
7041
  * Create a handler that invokes all added handler functions in parallel.
6642
7042
  * @param name
@@ -6667,6 +7067,13 @@ function createLiveSyncEventHub() {
6667
7067
 
6668
7068
  // lib/livesync-commonlib/src/services/base/CommonlibMessages.ts
6669
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.",
6670
7077
  "(BETA) Always overwrite with a newer file": "(BETA) Always overwrite with a newer file",
6671
7078
  "(Beta) Use ignore files": "(Beta) Use ignore files",
6672
7079
  "(Days passed, 0 to disable automatic-deletion)": "(Days passed, 0 to disable automatic-deletion)",
@@ -7077,7 +7484,7 @@ var AppLifecycleService = class extends ServiceBase {
7077
7484
  * Event triggered before the plug-in is unloaded.
7078
7485
  * This is typically used to perform any necessary cleanup or save state before the plug-in is unloaded.
7079
7486
  */
7080
- onBeforeUnload = handlers().all("onBeforeUnload");
7487
+ onBeforeUnload = handlers().allSettled("onBeforeUnload");
7081
7488
  /**
7082
7489
  * Event triggered when the plug-in is being unloaded.
7083
7490
  *
@@ -7233,10 +7640,18 @@ var FileProcessingService = class extends ServiceBase {
7233
7640
  */
7234
7641
  processFileEvent = handlers().anySuccess("processFileEvent");
7235
7642
  /**
7236
- * Process a file event item optionally, if any handler is registered.
7643
+ * Dispatch a legacy optional notification, without confirming persistence.
7237
7644
  * i.e., hidden files synchronisation or customisation sync.
7238
7645
  */
7239
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
+ );
7240
7655
  /**
7241
7656
  * Commit any pending file events that have been queued for processing.
7242
7657
  */
@@ -7279,9 +7694,9 @@ var PathService = class extends ServiceBase {
7279
7694
  const [prefix, path] = expandFilePathPrefix(filename);
7280
7695
  return prefix + this.normalizePath(path);
7281
7696
  }
7282
- async _path2id(filename, obfuscatePassphrase, caseInsensitive, idDerivationKey) {
7697
+ async _path2id(filename, obfuscatePassphrase, caseInsensitive, idDerivationKey, pathNormalizationVersion) {
7283
7698
  const [prefix, path] = expandFilePathPrefix(filename);
7284
- const fixedPath = prefix + this.normalizePath(path);
7699
+ const fixedPath = prefix + normalisePathForIdentity(this.normalizePath(path), pathNormalizationVersion);
7285
7700
  const out = await path2id_base(fixedPath, obfuscatePassphrase, caseInsensitive, idDerivationKey);
7286
7701
  return out;
7287
7702
  }
@@ -7310,13 +7725,15 @@ var PathService = class extends ServiceBase {
7310
7725
  }
7311
7726
  /** Convert a path using the caller's settings snapshot and this host's path normalisation. */
7312
7727
  async path2idWithSettings(filename, setting, prefix) {
7728
+ const pathNormalizationVersion = getPathNormalizationVersion(setting);
7313
7729
  const destPath = addPrefix(filename, prefix ?? "");
7314
7730
  const pathObfuscationPassphrase = this.getPathObfuscationPassphrase?.() ?? (setting.usePathObfuscation ? setting.passphrase : false);
7315
7731
  return await this._path2id(
7316
7732
  destPath,
7317
7733
  pathObfuscationPassphrase,
7318
7734
  !setting.handleFilenameCaseSensitive,
7319
- setting.encrypt && configuredIdKey(setting) || void 0
7735
+ setting.encrypt && configuredIdKey(setting) || void 0,
7736
+ pathNormalizationVersion
7320
7737
  );
7321
7738
  }
7322
7739
  getPath(entry) {
@@ -7567,6 +7984,40 @@ async function runWithTrackedPhysicalRequest(counters, task) {
7567
7984
  }
7568
7985
  }
7569
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
+
7570
8021
  // lib/livesync-commonlib/src/services/base/RemoteService.ts
7571
8022
  function createRemoteConnectionScope(ownerSignal) {
7572
8023
  const controller = new AbortController();
@@ -7743,6 +8194,12 @@ var RemoteService = class extends ServiceBase {
7743
8194
  return "Network is offline";
7744
8195
  }
7745
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
+ );
7746
8203
  const conf = {
7747
8204
  adapter: "http",
7748
8205
  auth: "username" in auth ? auth : void 0,
@@ -7777,11 +8234,12 @@ var RemoteService = class extends ServiceBase {
7777
8234
  if (!("username" in auth)) {
7778
8235
  headers.append("authorization", authHeader);
7779
8236
  }
8237
+ const cachedRequest = await prepareCachedRequest(requestSrc, opts);
7780
8238
  try {
7781
8239
  const signal = connectionScope.combine(opts?.signal);
7782
8240
  const response = await this.performFetch(
7783
- requestSrc,
7784
- { ...opts, headers, signal },
8241
+ cachedRequest.request,
8242
+ { ...opts, headers, signal, cache: cachedRequest.cache },
7785
8243
  useRequestAPI ? FetchMethod.native : FetchMethod.webCompat
7786
8244
  );
7787
8245
  return response;
@@ -7797,7 +8255,11 @@ var RemoteService = class extends ServiceBase {
7797
8255
  this._log(
7798
8256
  "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
7799
8257
  );
7800
- 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
+ );
7801
8263
  if (resp2.status / 100 == 2) {
7802
8264
  this.showError(
7803
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",
@@ -7830,7 +8292,6 @@ var RemoteService = class extends ServiceBase {
7830
8292
  }
7831
8293
  }
7832
8294
  };
7833
- const encryptionAlgorithm = connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;
7834
8295
  let db;
7835
8296
  try {
7836
8297
  db = new this._pouchDB(uri, conf);
@@ -7859,7 +8320,8 @@ var RemoteService = class extends ServiceBase {
7859
8320
  false,
7860
8321
  getPBKDF2Salt,
7861
8322
  encryptionAlgorithm,
7862
- connectionOptions.encryptInternalMetadata ?? false
8323
+ connectionOptions.encryptInternalMetadata ?? false,
8324
+ connectionOptions.acceptUnencryptedContent ?? false
7863
8325
  );
7864
8326
  }
7865
8327
  } catch (ex) {
@@ -8803,7 +9265,7 @@ var ActiveReplicatorState = class {
8803
9265
  // lib/livesync-commonlib/src/services/base/ReplicatorService.remoteResourceResolver.ts
8804
9266
  async function resolveRemoteResource(capabilities, kind, setting) {
8805
9267
  const capability = capabilities[kind];
8806
- if (capability.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
9268
+ if (capability?.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) {
8807
9269
  return void 0;
8808
9270
  }
8809
9271
  return await capability.run(setting);
@@ -9348,30 +9810,6 @@ var InjectableVaultServiceCompat = class extends InjectableVaultService {
9348
9810
  }
9349
9811
  };
9350
9812
 
9351
- // lib/livesync-commonlib/src/services/base/ConfigService.ts
9352
- var ConfigService = class extends ServiceBase {
9353
- };
9354
-
9355
- // lib/livesync-commonlib/src/services/implements/browser/ConfigServiceBrowserCompat.ts
9356
- var ConfigServiceBrowserCompat = class extends ConfigService {
9357
- _settingService;
9358
- _log;
9359
- constructor(context, dependencies) {
9360
- super(context);
9361
- this._settingService = dependencies.settingService;
9362
- this._log = createInstanceLogFunction("ConfigService", dependencies.APIService);
9363
- }
9364
- getSmallConfig(key) {
9365
- return this._settingService.getSmallConfig(key);
9366
- }
9367
- setSmallConfig(key, value) {
9368
- return this._settingService.setSmallConfig(key, value);
9369
- }
9370
- deleteSmallConfig(key) {
9371
- return this._settingService.deleteSmallConfig(key);
9372
- }
9373
- };
9374
-
9375
9813
  // lib/livesync-commonlib/src/services/base/ControlService.ts
9376
9814
  import { LOG_LEVEL_URGENT as LOG_LEVEL_URGENT2 } from "octagonal-wheels/common/logger";
9377
9815
  import { cancelAllPeriodicTask, cancelAllTasks } from "octagonal-wheels/concurrency/task";
@@ -9412,7 +9850,9 @@ var ControlService = class extends ServiceBase {
9412
9850
  await this.services.appLifecycleService.onSuspending();
9413
9851
  await this.services.settingService.onBeforeRealiseSetting();
9414
9852
  this.services.databaseService.localDatabase.refreshSettings();
9415
- 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
+ }
9416
9856
  await this.services.settingService.onRealiseSetting();
9417
9857
  if (this.services.appLifecycleService.isSuspended()) return;
9418
9858
  await this.services.appLifecycleService.onResuming();
@@ -9421,7 +9861,8 @@ var ControlService = class extends ServiceBase {
9421
9861
  }
9422
9862
  async _onLiveSyncUnload() {
9423
9863
  this.context.events.emitEvent(EVENT_PLUGIN_UNLOADED);
9424
- 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);
9425
9866
  await Promise.resolve(this.services.appLifecycleService.onAppUnload());
9426
9867
  cancelAllPeriodicTask();
9427
9868
  cancelAllTasks();
@@ -9436,6 +9877,7 @@ var ControlService = class extends ServiceBase {
9436
9877
  this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);
9437
9878
  this.context.events.offAll();
9438
9879
  this._log(this.context.translate("moduleLiveSyncMain.logUnloadingPlugin"));
9880
+ if (!prepared) throw new Error("Unload preparation failed");
9439
9881
  return;
9440
9882
  }
9441
9883
  /**
@@ -9643,12 +10085,67 @@ var InjectableServiceHub = class extends ServiceHub {
9643
10085
  }
9644
10086
  };
9645
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
+
9646
10140
  // lib/livesync-commonlib/src/services/implements/base/UIService.ts
9647
10141
  var UIService = class extends ServiceBase {
10142
+ commands;
9648
10143
  _dialogManager;
9649
10144
  _APIService;
9650
10145
  constructor(context, dependents) {
9651
10146
  super(context);
10147
+ this.commands = new UICommandRegistry();
10148
+ this.context.events.once(EVENT_PLUGIN_UNLOADED, () => this.commands.dispose());
9652
10149
  this._dialogManager = dependents.dialogManager;
9653
10150
  this._APIService = dependents.APIService;
9654
10151
  }
@@ -9688,6 +10185,18 @@ var APIService = class extends ServiceBase {
9688
10185
  showWindowOnRight(type) {
9689
10186
  return this.showWindow(type);
9690
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
+ }
9691
10200
  requestCount = reactiveSource6(0);
9692
10201
  responseCount = reactiveSource6(0);
9693
10202
  get isOnline() {
@@ -9959,6 +10468,15 @@ var KeyValueDBService = class extends ServiceBase {
9959
10468
  this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this));
9960
10469
  }
9961
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
+ */
9962
10480
  openSimpleStore(kind) {
9963
10481
  const getDB = () => {
9964
10482
  if (!this._kvDB) {
@@ -9978,8 +10496,9 @@ var KeyValueDBService = class extends ServiceBase {
9978
10496
  await getDB().del(`${prefix}${key}`);
9979
10497
  },
9980
10498
  keys: async (from, to, count) => {
10499
+ const upperBound = to === void 0 ? `${prefix.slice(0, -1)}.` : `${prefix}${to || ""}`;
9981
10500
  const ret = await getDB().keys(
9982
- IDBKeyRange.bound(`${prefix}${from || ""}`, `${prefix}${to || ""}`),
10501
+ IDBKeyRange.bound(`${prefix}${from || ""}`, upperBound, false, to === void 0),
9983
10502
  count
9984
10503
  );
9985
10504
  return ret.map((e) => (typeof e === "string" ? e : JSON.stringify(e)).toString()).filter((e) => e.startsWith(prefix)).map((e) => e.substring(prefix.length));
@@ -10125,12 +10644,15 @@ var HeadlessDatabaseService = class extends DatabaseService {
10125
10644
  var HeadlessKeyValueDBService = class extends KeyValueDBService {
10126
10645
  };
10127
10646
 
10647
+ // lib/livesync-commonlib/src/services/base/SettingService.ts
10648
+ import { createDeletableValueStore } from "@vrtmrz/value-store";
10649
+
10128
10650
  // lib/livesync-commonlib/src/encryption/stringEncryption.ts
10129
10651
  import {
10130
10652
  decrypt as decrypt3,
10131
- ENCRYPT_V2_PREFIX,
10132
- ENCRYPT_V3_PREFIX,
10133
- 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
10134
10656
  } from "octagonal-wheels/encryption/encryption";
10135
10657
  import {
10136
10658
  encryptWithEphemeralSalt,
@@ -10138,7 +10660,7 @@ import {
10138
10660
  HKDF_SALTED_ENCRYPTED_PREFIX
10139
10661
  } from "octagonal-wheels/encryption/hkdf";
10140
10662
  async function encryptString(source, passphrase) {
10141
- if (source.startsWith(ENCRYPT_V2_PREFIX)) {
10663
+ if (source.startsWith(ENCRYPT_V2_PREFIX3)) {
10142
10664
  return source;
10143
10665
  } else if (source.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {
10144
10666
  return source;
@@ -10160,7 +10682,7 @@ async function tryDecryption(trials) {
10160
10682
  async function decryptString(encrypted, passphrase) {
10161
10683
  if (encrypted.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)) {
10162
10684
  return decryptWithEphemeralSalt(encrypted, passphrase);
10163
- } 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)) {
10164
10686
  return await tryDecryption([
10165
10687
  async () => await decrypt3(encrypted, passphrase, false),
10166
10688
  async () => await decrypt3(encrypted, passphrase, true)
@@ -10172,7 +10694,12 @@ async function decryptString(encrypted, passphrase) {
10172
10694
  }
10173
10695
 
10174
10696
  // lib/livesync-commonlib/src/services/base/SettingService.ts
10175
- 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";
10176
10703
 
10177
10704
  // lib/livesync-commonlib/src/common/ConnectionString.ts
10178
10705
  var PROXY_SCHEME = "https";
@@ -10478,11 +11005,272 @@ function activateP2PRemoteConfiguration(settings, id) {
10478
11005
  }
10479
11006
  }
10480
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
+
10481
11263
  // lib/livesync-commonlib/src/services/base/SettingService.ts
11264
+ var ConfigurationPassphraseError = class extends Error {
11265
+ };
10482
11266
  var SettingService = class extends ServiceBase {
10483
11267
  deviceAndVaultName = "";
10484
11268
  APIService;
10485
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;
10486
11274
  _settings;
10487
11275
  get settings() {
10488
11276
  return this._settings;
@@ -10492,6 +11280,7 @@ var SettingService = class extends ServiceBase {
10492
11280
  }
10493
11281
  _lastPersistedSettings;
10494
11282
  _settingsMigrationState;
11283
+ saveQueue = Promise.resolve();
10495
11284
  getSettingsMigrationState() {
10496
11285
  return this._settingsMigrationState;
10497
11286
  }
@@ -10499,6 +11288,12 @@ var SettingService = class extends ServiceBase {
10499
11288
  constructor(context, dependencies) {
10500
11289
  super(context);
10501
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
+ });
10502
11297
  this.onDisplayLanguageChanged = dependencies.onDisplayLanguageChanged;
10503
11298
  this._log = createInstanceLogFunction("SettingService", this.APIService);
10504
11299
  }
@@ -10507,6 +11302,7 @@ var SettingService = class extends ServiceBase {
10507
11302
  * @param settings The settings to adjust.
10508
11303
  */
10509
11304
  adjustSettings(settings) {
11305
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(settings.acceptUnencryptedContent);
10510
11306
  if (migrateLegacyRemoteConfigurationsInPlace(settings, (message) => {
10511
11307
  this._log(message, LOG_LEVEL_NOTICE);
10512
11308
  })) {
@@ -10551,26 +11347,9 @@ var SettingService = class extends ServiceBase {
10551
11347
  /**
10552
11348
  * Save the current device and vault name to settings, aside from the main settings.
10553
11349
  */
10554
- saveDeviceAndVaultName() {
11350
+ async saveDeviceAndVaultName() {
10555
11351
  const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.APIService.getSystemVaultName() + this.additionalSuffixOfDatabaseName();
10556
- this.setDeviceLocalConfig(lsKey, this.deviceAndVaultName);
10557
- }
10558
- /**
10559
- * Read an exact key from the host's device-local configuration store.
10560
- *
10561
- * Unlike the main settings document, this state is not synchronised. Callers
10562
- * which need Vault namespacing should normally use {@link getSmallConfig}.
10563
- */
10564
- getDeviceLocalConfig(key) {
10565
- return this.getItem(key);
10566
- }
10567
- /** Store an exact key in the host's non-synchronised configuration store. */
10568
- setDeviceLocalConfig(key, value) {
10569
- this.setItem(key, value);
10570
- }
10571
- /** Delete an exact key from the host's non-synchronised configuration store. */
10572
- deleteDeviceLocalConfig(key) {
10573
- this.deleteItem(key);
11352
+ await this.deviceValues.setValue(lsKey, this.deviceAndVaultName);
10574
11353
  }
10575
11354
  additionalSuffixOfDatabaseName() {
10576
11355
  const suffix = this.settings?.additionalSuffixOfDatabaseName;
@@ -10585,46 +11364,134 @@ var SettingService = class extends ServiceBase {
10585
11364
  const addSuffix = this.additionalSuffixOfDatabaseName();
10586
11365
  return `${keyMain}${addSuffix}-${key}`;
10587
11366
  }
10588
- setSmallConfig(key, value) {
10589
- const dbKey = this.getKey(key);
10590
- this.setDeviceLocalConfig(dbKey, value);
10591
- }
10592
- getSmallConfig(key) {
10593
- const dbKey = this.getKey(key);
10594
- return this.getDeviceLocalConfig(dbKey) ?? "";
10595
- }
10596
- deleteSmallConfig(key) {
10597
- const dbKey = this.getKey(key);
10598
- this.deleteDeviceLocalConfig(dbKey);
10599
- }
10600
11367
  /**
10601
11368
  * Save the current settings to storage.
10602
11369
  */
10603
- async saveSettingData() {
10604
- 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) {
10605
11474
  const previousSettings = this._lastPersistedSettings ?? this.cloneSettings(this.settings);
10606
- const settings = this.cloneSettings(this.settings);
10607
11475
  const hookResults = await this.onBeforeSaveSettingData(settings, previousSettings);
11476
+ const savedPatch = {};
10608
11477
  for (const patch of hookResults) {
10609
11478
  if (patch instanceof Error || !patch) continue;
10610
11479
  Object.assign(settings, patch);
10611
- Object.assign(this.settings, patch);
11480
+ Object.assign(savedPatch, patch);
10612
11481
  }
11482
+ const runtime = this.cloneSettings(settings);
10613
11483
  const idKey = configuredIdKey(settings);
11484
+ const configurationPassphrase = selectedPassphrase ?? await this.getSavingPassphrase(settings);
10614
11485
  if (settings.idDerivationVersion === 1) {
10615
11486
  if (idKey === false) {
10616
11487
  throw new Error("The configured ID derivation key is unavailable.");
10617
11488
  }
10618
- let passphrase = this.usedPassphrase;
10619
- if (passphrase === "") {
10620
- passphrase = await this.getPassphrase(settings);
10621
- }
10622
- if (passphrase === false || passphrase === "") {
11489
+ if (!configurationPassphrase) {
10623
11490
  const message = "Failed to retrieve a passphrase for the ID derivation key. Settings were not saved.";
10624
11491
  this._log(message, LOG_LEVEL_URGENT);
10625
11492
  throw new Error(message);
10626
11493
  }
10627
- const encryptedIdKey = await encryptString(idKey, passphrase + SALT_OF_PASSPHRASE);
11494
+ const encryptedIdKey = await encryptString(idKey, configurationPassphrase + SALT_OF_PASSPHRASE);
10628
11495
  if (encryptedIdKey === "") {
10629
11496
  const message = "Failed to encrypt the ID derivation key. Settings were not saved.";
10630
11497
  this._log(message, LOG_LEVEL_URGENT);
@@ -10632,76 +11499,74 @@ var SettingService = class extends ServiceBase {
10632
11499
  }
10633
11500
  settings.encryptedIdDerivationKey = encryptedIdKey;
10634
11501
  settings.idDerivationKey = "";
10635
- this.usedPassphrase = passphrase;
10636
11502
  } else {
10637
11503
  settings.encryptedIdDerivationKey = "";
10638
11504
  }
10639
11505
  settings.deviceAndVaultName = "";
10640
11506
  if (settings.P2P_DevicePeerName && settings.P2P_DevicePeerName.trim() !== "") {
10641
- this._log("Saving device peer name to small config");
10642
- this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME, settings.P2P_DevicePeerName.trim());
10643
11507
  settings.P2P_DevicePeerName = "";
10644
11508
  }
10645
- delete settings.P2P_managedType;
10646
- delete settings.P2P_managedId;
10647
- delete settings.P2P_managedToken;
10648
- if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) {
11509
+ omitUnpersistedSettings(settings);
11510
+ if (!configurationPassphrase) {
10649
11511
  if (Object.values(settings.remoteConfigurations).some((config) => this.hasManagedP2PProfileURI(config.uri))) {
10650
11512
  const message = "Failed to retrieve a passphrase for managed P2P source data. Settings were not saved.";
10651
11513
  this._log(message, LOG_LEVEL_URGENT);
10652
11514
  throw new Error(message);
10653
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
+ }
10654
11523
  this._log("Failed to retrieve passphrase. data.json contains unencrypted items!", LOG_LEVEL_NOTICE);
10655
11524
  } else {
10656
- if (settings.couchDB_PASSWORD != "" || settings.couchDB_URI != "" || settings.couchDB_USER != "" || settings.couchDB_DBNAME) {
10657
- const connectionSetting = {
10658
- couchDB_DBNAME: settings.couchDB_DBNAME,
10659
- couchDB_PASSWORD: settings.couchDB_PASSWORD,
10660
- couchDB_URI: settings.couchDB_URI,
10661
- couchDB_USER: settings.couchDB_USER,
10662
- accessKey: settings.accessKey,
10663
- bucket: settings.bucket,
10664
- endpoint: settings.endpoint,
10665
- region: settings.region,
10666
- secretKey: settings.secretKey,
10667
- useCustomRequestHandler: settings.useCustomRequestHandler,
10668
- bucketCustomHeaders: settings.bucketCustomHeaders,
10669
- couchDB_CustomHeaders: settings.couchDB_CustomHeaders,
10670
- useJWT: settings.useJWT,
10671
- jwtKey: settings.jwtKey,
10672
- jwtAlgorithm: settings.jwtAlgorithm,
10673
- jwtKid: settings.jwtKid,
10674
- jwtExpDuration: settings.jwtExpDuration,
10675
- jwtSub: settings.jwtSub,
10676
- useRequestAPI: settings.useRequestAPI,
10677
- bucketPrefix: settings.bucketPrefix,
10678
- forcePathStyle: settings.forcePathStyle
10679
- };
10680
- settings.encryptedCouchDBConnection = await this.encryptConfigurationItem(
10681
- JSON.stringify(connectionSetting),
10682
- 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)
10683
11537
  );
10684
- settings.couchDB_PASSWORD = "";
10685
- settings.couchDB_DBNAME = "";
10686
- settings.couchDB_URI = "";
10687
- settings.couchDB_USER = "";
10688
- settings.accessKey = "";
10689
- settings.bucket = "";
10690
- settings.region = "";
10691
- settings.secretKey = "";
10692
- settings.endpoint = "";
11538
+ if (restoreConnectionSettings(this.cloneSettings(settings), existingConnection)) {
11539
+ settings.encryptedCouchDBConnection = "";
11540
+ }
10693
11541
  }
10694
11542
  if (settings.encrypt && settings.passphrase != "") {
10695
- settings.encryptedPassphrase = await this.encryptPlainConfigurationItem(settings.passphrase, settings);
11543
+ settings.encryptedPassphrase = requireConfigurationCiphertext(
11544
+ await this.encryptPlainConfigurationItem(settings.passphrase, settings, configurationPassphrase)
11545
+ );
10696
11546
  settings.passphrase = "";
10697
11547
  }
10698
- await this.encryptRemoteConfigurationUris(settings);
11548
+ await this.encryptRemoteConfigurationUris(settings, configurationPassphrase);
10699
11549
  }
10700
- await this.saveData(settings);
10701
- this._lastPersistedSettings = this.cloneSettings(this.settings);
10702
- void this.onSettingSaved(settings);
11550
+ const persisted = prepareSettingsForPersistence(settings);
11551
+ return { persisted, runtime, patch: savedPatch, passphrase: configurationPassphrase };
11552
+ }
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);
10703
11559
  }
10704
- async encryptRemoteConfigurationUris(settings) {
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) {
10705
11570
  const configs = settings.remoteConfigurations || {};
10706
11571
  for (const [id, config] of Object.entries(configs)) {
10707
11572
  if (config.isEncrypted || config.uri.trim() === "") {
@@ -10710,7 +11575,7 @@ var SettingService = class extends ServiceBase {
10710
11575
  const managedP2PProfile = this.hasManagedP2PProfileURI(config.uri);
10711
11576
  let encryptedURI;
10712
11577
  try {
10713
- encryptedURI = await this.encryptConfigurationItem(config.uri, settings);
11578
+ encryptedURI = await this.encryptConfigurationItem(config.uri, settings, passphrase);
10714
11579
  } catch (error) {
10715
11580
  if (managedP2PProfile) {
10716
11581
  const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
@@ -10725,6 +11590,11 @@ var SettingService = class extends ServiceBase {
10725
11590
  this._log(message, LOG_LEVEL_URGENT);
10726
11591
  throw new Error(message);
10727
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
+ }
10728
11598
  this._log(
10729
11599
  `Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`,
10730
11600
  LOG_LEVEL_URGENT
@@ -10747,6 +11617,7 @@ var SettingService = class extends ServiceBase {
10747
11617
  return (new URLSearchParams(query).get("managedType") ?? "").trim().length > 0;
10748
11618
  }
10749
11619
  async decryptRemoteConfigurationUris(settings, passphrase) {
11620
+ let verified = false;
10750
11621
  const configs = settings.remoteConfigurations || {};
10751
11622
  for (const [id, config] of Object.entries(configs)) {
10752
11623
  if (!config.isEncrypted) {
@@ -10778,7 +11649,9 @@ var SettingService = class extends ServiceBase {
10778
11649
  uri: decryptedURI,
10779
11650
  isEncrypted: false
10780
11651
  };
11652
+ verified = true;
10781
11653
  }
11654
+ return verified;
10782
11655
  }
10783
11656
  /**
10784
11657
  * Event triggered before realising the settings.
@@ -10862,25 +11735,38 @@ var SettingService = class extends ServiceBase {
10862
11735
  getPassphrase(settings) {
10863
11736
  const methods = {
10864
11737
  "": () => Promise.resolve("*"),
10865
- LOCALSTORAGE: () => Promise.resolve(this.getDeviceLocalConfig("ls-setting-passphrase") ?? false),
10866
- 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
+ )
10867
11745
  };
10868
11746
  const method = settings.configPassphraseStore;
10869
11747
  const methodFunc = method in methods ? methods[method] : methods[""];
10870
11748
  return methodFunc();
10871
11749
  }
10872
- 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
+ }
10873
11760
  /**
10874
11761
  * Clear any used passphrase from memory.
10875
11762
  */
10876
11763
  clearUsedPassphrase() {
10877
- this.usedPassphrase = "";
11764
+ this.usedPassphrase = void 0;
10878
11765
  }
10879
11766
  async decryptConfigurationItem(encrypted, passphrase) {
10880
11767
  try {
10881
11768
  const dec = await decryptString(encrypted, passphrase + SALT_OF_PASSPHRASE);
10882
11769
  if (dec) {
10883
- this.usedPassphrase = passphrase;
10884
11770
  return dec;
10885
11771
  }
10886
11772
  } catch (ex) {
@@ -10889,18 +11775,15 @@ var SettingService = class extends ServiceBase {
10889
11775
  }
10890
11776
  return false;
10891
11777
  }
10892
- async encryptConfigurationItem(src, settings) {
10893
- return this.encryptConfigurationItemWith(src, settings, encryptString);
11778
+ async encryptConfigurationItem(src, settings, passphrase) {
11779
+ return this.encryptConfigurationItemWith(src, settings, encryptString, passphrase);
10894
11780
  }
10895
- async encryptPlainConfigurationItem(src, settings) {
10896
- return this.encryptConfigurationItemWith(src, settings, encryptWithEphemeralSalt2);
11781
+ async encryptPlainConfigurationItem(src, settings, passphrase) {
11782
+ return this.encryptConfigurationItemWith(src, settings, encryptWithEphemeralSalt2, passphrase);
10897
11783
  }
10898
- async encryptConfigurationItemWith(src, settings, encrypt3) {
10899
- if (this.usedPassphrase != "") {
10900
- return await encrypt3(src, this.usedPassphrase + SALT_OF_PASSPHRASE);
10901
- }
10902
- const passphrase = await this.getPassphrase(settings);
10903
- if (passphrase === false) {
11784
+ async encryptConfigurationItemWith(src, settings, encrypt3, selectedPassphrase) {
11785
+ const passphrase = selectedPassphrase ?? await this.getSavingPassphrase(settings);
11786
+ if (!passphrase) {
10904
11787
  this._log(
10905
11788
  "Failed to obtain passphrase when saving data.json! Please verify the configuration.",
10906
11789
  LOG_LEVEL_URGENT
@@ -10909,7 +11792,7 @@ var SettingService = class extends ServiceBase {
10909
11792
  }
10910
11793
  const dec = await encrypt3(src, passphrase + SALT_OF_PASSPHRASE);
10911
11794
  if (dec) {
10912
- this.usedPassphrase = passphrase;
11795
+ if (selectedPassphrase === void 0) this.rememberPassphrase(settings, passphrase);
10913
11796
  return dec;
10914
11797
  }
10915
11798
  return "";
@@ -10919,19 +11802,24 @@ var SettingService = class extends ServiceBase {
10919
11802
  * @param settings The settings to decrypt.
10920
11803
  */
10921
11804
  async decryptSettings(settings) {
10922
- if (settings.idDerivationVersion !== 1) {
10923
- configuredIdKey(settings);
10924
- } else if (!settings.encryptedIdDerivationKey) {
10925
- throw new Error("The configured ID derivation key is missing or unavailable.");
10926
- }
11805
+ this.validateStoredIdConfiguration(settings);
10927
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);
10928
11814
  if (settings.idDerivationVersion === 1) {
10929
11815
  if (passphrase === false || passphrase === "") {
10930
- 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
+ );
10931
11819
  }
10932
11820
  const decryptedIdKey = await this.decryptConfigurationItem(settings.encryptedIdDerivationKey, passphrase);
10933
11821
  if (decryptedIdKey === false) {
10934
- 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.");
10935
11823
  }
10936
11824
  try {
10937
11825
  configuredIdKey({ ...settings, idDerivationKey: decryptedIdKey });
@@ -10939,6 +11827,7 @@ var SettingService = class extends ServiceBase {
10939
11827
  throw new Error("The configured ID derivation key is invalid.");
10940
11828
  }
10941
11829
  settings.idDerivationKey = decryptedIdKey;
11830
+ verified = true;
10942
11831
  }
10943
11832
  if (passphrase === false) {
10944
11833
  this._log("No passphrase found for data.json! Verify configuration before syncing.", LOG_LEVEL_URGENT);
@@ -10953,34 +11842,17 @@ var SettingService = class extends ServiceBase {
10953
11842
  }
10954
11843
  } else {
10955
11844
  if (settings.encryptedCouchDBConnection) {
10956
- const keys = [
10957
- "couchDB_URI",
10958
- "couchDB_USER",
10959
- "couchDB_PASSWORD",
10960
- "couchDB_DBNAME",
10961
- "accessKey",
10962
- "bucket",
10963
- "endpoint",
10964
- "region",
10965
- "secretKey"
10966
- ];
10967
11845
  const decrypted = this.tryDecodeJson(
10968
11846
  await this.decryptConfigurationItem(settings.encryptedCouchDBConnection, passphrase)
10969
11847
  );
10970
- if (decrypted) {
10971
- for (const key of keys) {
10972
- if (key in decrypted) {
10973
- settings[key] = decrypted[key];
10974
- }
10975
- }
10976
- } else {
11848
+ if (!restoreConnectionSettings(settings, decrypted)) {
10977
11849
  this._log(
10978
11850
  "Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",
10979
11851
  LOG_LEVEL_URGENT
10980
11852
  );
10981
- for (const key of keys) {
10982
- settings[key] = "";
10983
- }
11853
+ clearConnectionSettings(settings);
11854
+ } else {
11855
+ verified = true;
10984
11856
  }
10985
11857
  }
10986
11858
  if (settings.encrypt && settings.encryptedPassphrase) {
@@ -10988,6 +11860,7 @@ var SettingService = class extends ServiceBase {
10988
11860
  const decrypted = await this.decryptConfigurationItem(encrypted, passphrase);
10989
11861
  if (decrypted) {
10990
11862
  settings.passphrase = decrypted;
11863
+ verified = true;
10991
11864
  } else {
10992
11865
  this._log(
10993
11866
  "Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",
@@ -10996,9 +11869,80 @@ var SettingService = class extends ServiceBase {
10996
11869
  settings.passphrase = "";
10997
11870
  }
10998
11871
  }
10999
- 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
+ }
11000
11945
  }
11001
- return settings;
11002
11946
  }
11003
11947
  async loadSettings() {
11004
11948
  const prepared = prepareSettingsForLoad(await this.loadData());
@@ -11014,7 +11958,7 @@ var SettingService = class extends ServiceBase {
11014
11958
  settings.isConfigured = false;
11015
11959
  }
11016
11960
  }
11017
- this.settings = await this.decryptSettings(settings);
11961
+ this.settings = await this.loadConfiguration(settings);
11018
11962
  this.onDisplayLanguageChanged?.(this.settings.displayLanguage);
11019
11963
  await this.adjustSettings(this.settings);
11020
11964
  const migratedLegacyRemoteConfigurations = !hadRemoteConfigurations && Object.keys(this.settings.remoteConfigurations ?? {}).length > 0;
@@ -11051,9 +11995,9 @@ var SettingService = class extends ServiceBase {
11051
11995
  }
11052
11996
  const lsKey = "obsidian-live-sync-vaultanddevicename-" + this.APIService.getSystemVaultName() + this.additionalSuffixOfDatabaseName();
11053
11997
  if (this.settings.deviceAndVaultName != "") {
11054
- if (!this.getDeviceLocalConfig(lsKey)) {
11998
+ if (!await this.deviceValues.getValue(lsKey)) {
11055
11999
  this.setDeviceAndVaultName(this.settings.deviceAndVaultName);
11056
- this.saveDeviceAndVaultName();
12000
+ await this.saveDeviceAndVaultName();
11057
12001
  this.settings.deviceAndVaultName = "";
11058
12002
  }
11059
12003
  }
@@ -11064,7 +12008,7 @@ var SettingService = class extends ServiceBase {
11064
12008
  );
11065
12009
  this.settings.customChunkSize = 0;
11066
12010
  }
11067
- this.setDeviceAndVaultName(this.getDeviceLocalConfig(lsKey) || "");
12011
+ this.setDeviceAndVaultName(await this.deviceValues.getValue(lsKey) || "");
11068
12012
  if (this.getDeviceAndVaultName() == "") {
11069
12013
  if (this.settings.usePluginSync) {
11070
12014
  this._log("Device name missing. Disabling plug-in sync.", LOG_LEVEL_NOTICE);
@@ -11110,16 +12054,6 @@ var InjectableSettingService = class extends SettingService {
11110
12054
  return Promise.resolve(true);
11111
12055
  });
11112
12056
  }
11113
- setItem(key, value) {
11114
- return compatGlobal.localStorage.setItem(key, value);
11115
- }
11116
- getItem(key) {
11117
- return compatGlobal.localStorage.getItem(key) ?? "";
11118
- }
11119
- deleteItem(key) {
11120
- compatGlobal.localStorage.removeItem(key);
11121
- }
11122
- // override currentSettings = handlers<SettingService<T>>().binder("currentSettings");
11123
12057
  saveData = handlers().binder("saveData");
11124
12058
  loadData = handlers().binder("loadData");
11125
12059
  };
@@ -11534,6 +12468,7 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11534
12468
  const fileProcessing = new InjectableFileProcessingService(context);
11535
12469
  const setting = new InjectableSettingService(context, {
11536
12470
  APIService: API,
12471
+ deviceValues: overrideServiceConstructor.deviceValues,
11537
12472
  onDisplayLanguageChanged: overrideServiceConstructor.onDisplayLanguageChanged
11538
12473
  });
11539
12474
  const appLifecycle = new HeadlessAppLifecycleService(context, {
@@ -11563,10 +12498,7 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11563
12498
  vault,
11564
12499
  setting
11565
12500
  });
11566
- const config = new ConfigServiceBrowserCompat(context, {
11567
- settingService: setting,
11568
- APIService: API
11569
- });
12501
+ const config = setting.config;
11570
12502
  const replicator = new InjectableReplicatorService(context, {
11571
12503
  settingService: setting,
11572
12504
  appLifecycleService: appLifecycle,
@@ -11623,11 +12555,260 @@ var HeadlessServiceHub = class extends InjectableServiceHub {
11623
12555
  }
11624
12556
  };
11625
12557
 
11626
- // 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";
11627
12562
  function isNoteEntry(doc) {
11628
- if (!doc) return false;
11629
- 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();
11630
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
+ }
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
11631
12812
  function isReadyEntry(doc) {
11632
12813
  if (!doc) return false;
11633
12814
  return "data" in doc;
@@ -11656,6 +12837,7 @@ var DirectFileManipulator = class {
11656
12837
  if (idCompatibility === "mismatched") {
11657
12838
  throw new Error("Direct database document IDs do not match the configured ID key.");
11658
12839
  }
12840
+ await assertDatabasePathIdentity(this.liveSyncLocalDB.localDatabase, idSettings);
11659
12841
  const requiredFeatures = requiredRemoteFeatures(this.settings);
11660
12842
  if (!await checkRemoteVersion(
11661
12843
  this.liveSyncLocalDB.localDatabase,
@@ -11693,6 +12875,7 @@ var DirectFileManipulator = class {
11693
12875
  const getSettings = () => this.settings;
11694
12876
  const context = new ServiceContext();
11695
12877
  this.services = new HeadlessServiceHub(context, {
12878
+ deviceValues: new MemoryValueStore(),
11696
12879
  pouchDB: PouchDB,
11697
12880
  database: this.getBoundDatabaseService(() => this.options, this.runtimeOptions),
11698
12881
  getPathObfuscationPassphrase: () => this.options.obfuscatePassphrase ?? false,
@@ -11708,7 +12891,9 @@ var DirectFileManipulator = class {
11708
12891
  });
11709
12892
  this.services.setting.settings = getSettings();
11710
12893
  this.services.databaseEvents.onDatabaseInitialisation.addHandler(this.$everyOnInitializeDatabase.bind(this));
11711
- this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this);
12894
+ this.liveSyncLocalDB = new LiveSyncLocalDB(this.options.url, this, {
12895
+ createChunkFetchSource: createDirectChunkFetchSource
12896
+ });
11712
12897
  void this.ready.promise.catch(() => {
11713
12898
  });
11714
12899
  void this.init();
@@ -11741,7 +12926,7 @@ var DirectFileManipulator = class {
11741
12926
  }
11742
12927
  return downloadedSyncParams;
11743
12928
  } catch (ex) {
11744
- Logger19(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO6);
12929
+ Logger20(`Could not retrieve remote sync parameters`, LOG_LEVEL_INFO6);
11745
12930
  throw SyncParamsFetchError.fromError(ex);
11746
12931
  }
11747
12932
  }
@@ -11753,7 +12938,7 @@ var DirectFileManipulator = class {
11753
12938
  }
11754
12939
  throw new SyncParamsUpdateError(`Could not store remote sync parameters`);
11755
12940
  } catch (ex) {
11756
- Logger19(`Could not store remote sync parameters`, LOG_LEVEL_INFO6);
12941
+ Logger20(`Could not store remote sync parameters`, LOG_LEVEL_INFO6);
11757
12942
  throw SyncParamsUpdateError.fromError(ex);
11758
12943
  }
11759
12944
  }
@@ -11777,7 +12962,8 @@ var DirectFileManipulator = class {
11777
12962
  false,
11778
12963
  async () => await this.getReplicationPBKDF2Salt(this.getSettings()),
11779
12964
  this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2,
11780
- usesEncryptedInternalMetadata(this.settings)
12965
+ usesEncryptedInternalMetadata(this.settings),
12966
+ this.options.acceptUnencryptedContent ?? false
11781
12967
  );
11782
12968
  }
11783
12969
  return Promise.resolve(true);
@@ -11786,6 +12972,7 @@ var DirectFileManipulator = class {
11786
12972
  return this.settings;
11787
12973
  }
11788
12974
  async close() {
12975
+ this.endWatch();
11789
12976
  await this.liveSyncLocalDB.close();
11790
12977
  return this.liveSyncLocalDB.onunload();
11791
12978
  }
@@ -11801,6 +12988,9 @@ var DirectFileManipulator = class {
11801
12988
  passphrase: this.options.passphrase ?? "",
11802
12989
  idDerivationVersion: this.options.idDerivationVersion ?? 0,
11803
12990
  idDerivationKey: this.options.idDerivationKey ?? "",
12991
+ pathNormalizationVersion: getPathNormalizationVersion({
12992
+ pathNormalizationVersion: this.options.pathNormalizationVersion
12993
+ }),
11804
12994
  deleteMetadataOfDeletedFiles: DEFAULT_SETTINGS.deleteMetadataOfDeletedFiles,
11805
12995
  customChunkSize: this.options.customChunkSize ?? DEFAULT_SETTINGS.customChunkSize,
11806
12996
  doNotPaceReplication: DEFAULT_SETTINGS.doNotPaceReplication,
@@ -11827,6 +13017,8 @@ var DirectFileManipulator = class {
11827
13017
  handleFilenameCaseSensitive: this.options.handleFilenameCaseSensitive ?? DEFAULT_SETTINGS.handleFilenameCaseSensitive,
11828
13018
  usePathObfuscation: !!this.options.obfuscatePassphrase,
11829
13019
  encryptInternalMetadata: this.options.encryptInternalMetadata ?? false,
13020
+ acceptUnencryptedContent: this.options.acceptUnencryptedContent ?? DEFAULT_SETTINGS.acceptUnencryptedContent,
13021
+ syncInternalFiles: this.options.syncInternalFiles ?? DEFAULT_SETTINGS.syncInternalFiles,
11830
13022
  E2EEAlgorithm: this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2
11831
13023
  }
11832
13024
  };
@@ -11901,24 +13093,24 @@ var DirectFileManipulator = class {
11901
13093
  children: [],
11902
13094
  datatype
11903
13095
  };
11904
- Logger19(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE21);
13096
+ Logger20(`PUT: UPLOADING: ${path}`, LOG_LEVEL_VERBOSE21);
11905
13097
  const ret = await this.liveSyncLocalDB.putDBEntry(putDoc);
11906
13098
  if (ret) {
11907
- Logger19(`PUT: DONE: ${path}`, LOG_LEVEL_INFO6);
13099
+ Logger20(`PUT: DONE: ${path}`, LOG_LEVEL_INFO6);
11908
13100
  return true;
11909
13101
  } else {
11910
- Logger19(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE9);
13102
+ Logger20(`PUT: FAILED: ${path}`, LOG_LEVEL_NOTICE10);
11911
13103
  return false;
11912
13104
  }
11913
13105
  }
11914
13106
  async delete(path) {
11915
- Logger19(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE21);
13107
+ Logger20(`DELETE: START: ${path}`, LOG_LEVEL_VERBOSE21);
11916
13108
  const ret = await this.liveSyncLocalDB.deleteDBEntry(path);
11917
13109
  if (ret) {
11918
- Logger19(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO6);
13110
+ Logger20(`DELETE: DONE: ${path}`, LOG_LEVEL_INFO6);
11919
13111
  return true;
11920
13112
  } else {
11921
- Logger19(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO6);
13113
+ Logger20(`DELETE: FAILED: ${path}`, LOG_LEVEL_INFO6);
11922
13114
  return false;
11923
13115
  }
11924
13116
  }
@@ -11946,81 +13138,60 @@ var DirectFileManipulator = class {
11946
13138
  }
11947
13139
  }
11948
13140
  watching = false;
11949
- // _abortController?: AbortController;
11950
13141
  changes;
11951
13142
  since = "";
11952
- beginWatch(callback, checkIsInterested) {
11953
- if (this.watching) return false;
11954
- this.watching = true;
11955
- this.changes = this.liveSyncLocalDB.localDatabase.changes({
11956
- include_docs: true,
11957
- since: this.since,
11958
- selector: {
11959
- type: { $ne: "leaf" }
11960
- },
11961
- live: true
11962
- }).on("change", async (change) => {
11963
- const doc = change.doc;
11964
- if (!doc) {
11965
- return;
11966
- }
11967
- if (!isNoteEntry(doc)) {
11968
- return;
11969
- }
11970
- if (checkIsInterested) {
11971
- if (!checkIsInterested(doc)) {
11972
- Logger19(`WATCH: SKIP ${doc.path}: OUT OF TARGET FOLDER`, LOG_LEVEL_VERBOSE21, "watch");
11973
- 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;
11974
13170
  }
11975
- }
11976
- Logger19(`WATCH: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
11977
- let docX;
11978
- try {
11979
- docX = await this.getByMeta(doc);
11980
- } catch (ex) {
11981
- Logger19(`WATCH: DOCUMENT LOAD FAILED: ${doc.path}`, LEVEL_INFO2, "watch");
11982
- Logger19(ex, LEVEL_VERBOSE, "watch");
11983
- return;
11984
- }
11985
- try {
11986
- await callback(docX, change.seq);
11987
- Logger19(`WATCH: PROCESS DONE: ${doc.path}`, LEVEL_INFO2, "watch");
11988
- } catch (ex) {
11989
- Logger19(`WATCH: PROCESS FAILED`, LEVEL_INFO2, "watch");
11990
- Logger19(ex, LEVEL_VERBOSE, "watch");
11991
- }
11992
- }).on("complete", () => {
11993
- Logger19(`WATCH: FINISHED`, LEVEL_INFO2, "watch");
11994
- this.watching = false;
11995
- this.changes = void 0;
11996
- }).on("error", (err) => {
11997
- Logger19(`WATCH: ERROR: `, LEVEL_INFO2, "watch");
11998
- Logger19(err, LEVEL_VERBOSE, "watch");
11999
- if (this.watching) {
12000
- Logger19(`WATCH: CONNECTION HAS BEEN CLOSED, RECONNECTING...`, LEVEL_INFO2, "watch");
12001
- this.watching = false;
12002
- this.changes = void 0;
12003
- compatGlobal.setTimeout(() => {
12004
- this.beginWatch(callback, checkIsInterested);
12005
- }, 1e4);
12006
- } else {
12007
- 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);
12008
13182
  }
12009
13183
  });
13184
+ return this.watchOwner.beginWatch(callback, checkIsInterested, onCheckpoint);
12010
13185
  }
12011
13186
  endWatch() {
12012
- if (this.changes) {
12013
- Logger19(`WATCH: CANCELLING PROCESS.`, LEVEL_INFO2, "watch");
12014
- this.changes.cancel();
12015
- Logger19(`WATCH: CANCELLING SIGNAL HAS BEEN SENT.`, LEVEL_INFO2, "watch");
12016
- }
13187
+ this.watchOwner?.endWatch();
12017
13188
  }
12018
13189
  async followUpdates(callback, checkIsInterested) {
12019
13190
  try {
12020
13191
  if (this.since == "") {
12021
13192
  this.since = "0";
12022
13193
  }
12023
- Logger19(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO2, "followUpdates");
13194
+ Logger20(`FOLLOW: START: (since:${this.since})`, LEVEL_INFO3, "followUpdates");
12024
13195
  const last = await this.liveSyncLocalDB.localDatabase.changes({
12025
13196
  include_docs: true,
12026
13197
  since: this.since,
@@ -12036,29 +13207,29 @@ var DirectFileManipulator = class {
12036
13207
  }
12037
13208
  if (checkIsInterested) {
12038
13209
  if (!checkIsInterested(doc)) {
12039
- 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");
12040
13211
  return;
12041
13212
  }
12042
13213
  }
12043
- Logger19(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE, "watch");
13214
+ Logger20(`FOLLOW: PROCESSING: ${doc.path}`, LEVEL_VERBOSE2, "watch");
12044
13215
  const docX = await this.getByMeta(doc);
12045
13216
  try {
12046
13217
  await callback(docX, change.seq);
12047
- Logger19(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO2, "watch");
13218
+ Logger20(`FOLLOW: PROCESS DONE: ${doc.path}`, LEVEL_INFO3, "watch");
12048
13219
  } catch (ex) {
12049
- Logger19(`FOLLOW: PROCESS FAILED`, LEVEL_INFO2, "watch");
12050
- Logger19(ex, LEVEL_VERBOSE, "watch");
13220
+ Logger20(`FOLLOW: PROCESS FAILED`, LEVEL_INFO3, "watch");
13221
+ Logger20(ex, LEVEL_VERBOSE2, "watch");
12051
13222
  }
12052
13223
  }).on("complete", () => {
12053
- Logger19(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO2, "watch");
13224
+ Logger20(`FOLLOW: FINISHED AT ${this.since}`, LEVEL_INFO3, "watch");
12054
13225
  this.watching = false;
12055
13226
  this.changes = void 0;
12056
13227
  }).on("error", (err) => {
12057
- Logger19(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO2, "watch");
13228
+ Logger20(`FOLLOW: ERROR at ${this.since}: ${err}`, LEVEL_INFO3, "watch");
12058
13229
  });
12059
13230
  return last.last_seq;
12060
13231
  } catch (e) {
12061
- Logger19(`FOLLOW: ERROR: ${e}`, LEVEL_INFO2, "watch");
13232
+ Logger20(`FOLLOW: ERROR: ${e}`, LEVEL_INFO3, "watch");
12062
13233
  }
12063
13234
  return this.since;
12064
13235
  }
@@ -12180,13 +13351,17 @@ var Vault = class _Vault {
12180
13351
  // Obfuscation actually in effect after reconciling with the database, which
12181
13352
  // can differ from the configured value.
12182
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;
12183
13358
  // Serializes attachment writes per document id (see writeAttachmentUnlocked).
12184
13359
  attachmentLock = new KeyedLock();
12185
13360
  constructor(config) {
12186
13361
  this.config = config;
12187
13362
  this.passphrase = config.passphrase;
12188
13363
  }
12189
- static buildOptions(config, obfuscatePaths, idDerivationKey) {
13364
+ static buildOptions(config, obfuscatePaths, idDerivationKey, pathNormalizationVersion) {
12190
13365
  return {
12191
13366
  url: config.couchdbUrl,
12192
13367
  username: config.couchdbUser,
@@ -12198,6 +13373,7 @@ var Vault = class _Vault {
12198
13373
  enableCompression: false,
12199
13374
  handleFilenameCaseSensitive: !!config.caseSensitive,
12200
13375
  doNotUseFixedRevisionForChunks: false,
13376
+ pathNormalizationVersion,
12201
13377
  ...idDerivationOptions(obfuscatePaths, idDerivationKey)
12202
13378
  };
12203
13379
  }
@@ -12212,7 +13388,11 @@ var Vault = class _Vault {
12212
13388
  username: this.config.couchdbUser,
12213
13389
  password: this.config.couchdbPassword
12214
13390
  });
12215
- 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));
12216
13396
  await this.awaitManipulatorReady();
12217
13397
  await this.reconcileObfuscation();
12218
13398
  if (this.idDerivationKey && !this.obfuscatePathsEffective) {
@@ -12221,6 +13401,26 @@ var Vault = class _Vault {
12221
13401
  );
12222
13402
  }
12223
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
+ }
12224
13424
  /**
12225
13425
  * Await the manipulator's readiness, translating the library's ID-mismatch
12226
13426
  * error into actionable guidance. The library (0.1.34+) verifies at startup
@@ -12267,8 +13467,8 @@ var Vault = class _Vault {
12267
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."
12268
13468
  );
12269
13469
  this.obfuscatePathsEffective = actual;
12270
- await this.manipulator.close();
12271
- 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));
12272
13472
  await this.awaitManipulatorReady();
12273
13473
  }
12274
13474
  /** Sample file-entry docs from the changes feed and classify their IDs. */
@@ -12296,8 +13496,25 @@ var Vault = class _Vault {
12296
13496
  return classifyIds(ids);
12297
13497
  }
12298
13498
  async close() {
12299
- this.manipulator.endWatch();
12300
- 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();
12301
13518
  }
12302
13519
  static mdFilter(meta) {
12303
13520
  return isValidNotePath(meta.path ?? "");
@@ -12538,4 +13755,4 @@ var Vault = class _Vault {
12538
13755
  export {
12539
13756
  Vault
12540
13757
  };
12541
- //# sourceMappingURL=vault-7FFBJ5QT.js.map
13758
+ //# sourceMappingURL=vault-XZDTCOVA.js.map