@vrtmrz/livesync-commonlib 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +7 -5
  2. package/dist/API/DirectFileManipulatorV2.d.ts +1 -0
  3. package/dist/API/DirectFileManipulatorV2.js +3 -1
  4. package/dist/API/processSetting.d.ts +1 -0
  5. package/dist/API/processSetting.js +3 -0
  6. package/dist/common/models/setting.const.defaults.js +1 -0
  7. package/dist/common/models/setting.const.qr.js +2 -1
  8. package/dist/common/models/setting.encryption.d.ts +2 -0
  9. package/dist/common/models/setting.encryption.js +6 -0
  10. package/dist/common/models/setting.lifecycle.js +7 -2
  11. package/dist/common/models/setting.policy.d.ts +4 -0
  12. package/dist/common/models/setting.policy.js +9 -0
  13. package/dist/common/models/setting.type.d.ts +2 -0
  14. package/dist/common/models/shared.definition.configNames.js +5 -0
  15. package/dist/common/models/tweak.definition.d.ts +1 -0
  16. package/dist/common/settingConstants.d.ts +1 -0
  17. package/dist/common/utils.js +5 -4
  18. package/dist/diagnostics/couchdb.js +4 -2
  19. package/dist/interfaces/StorageAccess.d.ts +8 -2
  20. package/dist/managers/ChunkFetcher.js +27 -4
  21. package/dist/managers/chunkFetcher.helper.js +1 -1
  22. package/dist/platform/FilePathIndex.d.ts +110 -0
  23. package/dist/platform/FilePathIndex.js +146 -0
  24. package/dist/pouchdb/StreamingFetch.d.ts +1 -2
  25. package/dist/pouchdb/encryption.d.ts +5 -10
  26. package/dist/pouchdb/encryption.eden.d.ts +11 -0
  27. package/dist/pouchdb/encryption.eden.js +37 -0
  28. package/dist/pouchdb/encryption.js +67 -63
  29. package/dist/pouchdb/encryption.policy.d.ts +9 -0
  30. package/dist/pouchdb/encryption.policy.js +125 -0
  31. package/dist/replication/UnencryptedContentRejectedError.d.ts +16 -0
  32. package/dist/replication/UnencryptedContentRejectedError.js +44 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.js +41 -4
  34. package/dist/replication/index.d.ts +2 -0
  35. package/dist/replication/index.js +3 -0
  36. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  37. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  38. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  39. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  40. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  41. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  42. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  43. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  44. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  45. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  46. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  47. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  48. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  49. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  50. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  51. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  52. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  53. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -481
  54. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  55. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  56. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  57. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  58. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  59. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  60. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  61. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  62. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  63. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  64. package/dist/replication/trystero/replicationTypes.js +0 -0
  65. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  66. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  67. package/dist/replication/unencryptedContentMessages.d.ts +8 -0
  68. package/dist/replication/unencryptedContentMessages.js +12 -0
  69. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  70. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  71. package/dist/rpc/RpcRoom.d.ts +9 -4
  72. package/dist/rpc/RpcRoom.js +73 -118
  73. package/dist/rpc/RpcSession.d.ts +6 -0
  74. package/dist/rpc/RpcSession.js +11 -0
  75. package/dist/rpc/types.d.ts +2 -0
  76. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  77. package/dist/serviceFeatures/targetFilter.js +8 -38
  78. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  79. package/dist/serviceModules/FileAccessBase.js +10 -0
  80. package/dist/serviceModules/Rebuilder.js +29 -5
  81. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  82. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  83. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  84. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  85. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  86. package/dist/services/base/RemoteConnection.d.ts +2 -0
  87. package/dist/services/base/RemoteService.js +2 -1
  88. package/dist/services/base/SettingService.js +2 -0
  89. package/dist/settings.d.ts +2 -1
  90. package/dist/settings.js +2 -0
  91. package/dist/storage.d.ts +2 -0
  92. package/dist/storage.js +2 -0
  93. package/dist/worker/bgWorker.js +1 -1
  94. package/docs/development.md +103 -0
  95. package/docs/offline-scanner.md +2 -1
  96. package/docs/p2p-transport-lifecycle.md +24 -0
  97. package/docs/platform-storage.md +22 -0
  98. package/docs/releasing.md +6 -0
  99. package/docs/settings-lifecycle.md +6 -0
  100. package/package.json +1 -1
package/README.md CHANGED
@@ -14,9 +14,9 @@ This package is primarily for maintainers of those clients and for integrations
14
14
 
15
15
  ## Status and versioning
16
16
 
17
- Commonlib [0.4.1](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib/v/0.4.1)
17
+ Commonlib [0.4.3](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib/v/0.4.3)
18
18
  is published on npm through `latest` and `next`
19
- ([release notes](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.1)).
19
+ ([release notes](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.3)).
20
20
 
21
21
  Self-hosted LiveSync
22
22
  [1.0.44](https://github.com/vrtmrz/obsidian-livesync/releases/tag/1.0.44)
@@ -272,10 +272,12 @@ standardIo.writeStdout("ready\n");
272
272
 
273
273
  See [the standard-I/O contract](docs/platform-standard-io.md) for host composition and test-double examples.
274
274
 
275
- ## Ordinary deletion recovery (unreleased)
275
+ <a id="ordinary-deletion-recovery-unreleased"></a>
276
276
 
277
- Hosts using the ordinary file handler can opt in to recovery of retained logical
278
- deletions by supplying provenance key enumeration. Recovery preserves edited or
277
+ ## Ordinary deletion recovery
278
+
279
+ Available in Commonlib 0.4.2. Hosts using the ordinary file handler can opt in to
280
+ recovery of retained logical deletions by supplying provenance key enumeration. Recovery preserves edited or
279
281
  unproven files, uses existing Chunk delivery policy, and reports physical removal
280
282
  and interrupted bookkeeping separately. Hosts which do not opt in retain their
281
283
  existing scanner policy. See [the recovery contract](docs/deletion-recovery.md)
@@ -17,6 +17,7 @@ export type DirectFileManipulatorOptions = {
17
17
  idDerivationKey?: string;
18
18
  pathNormalizationVersion?: 0 | 1;
19
19
  encryptInternalMetadata?: boolean;
20
+ acceptUnencryptedContent?: boolean;
20
21
  useDynamicIterationCount?: boolean;
21
22
  customChunkSize?: number;
22
23
  minimumChunkSize?: number;
@@ -195,7 +195,8 @@ class DirectFileManipulator {
195
195
  false,
196
196
  async () => await this.getReplicationPBKDF2Salt(this.getSettings()),
197
197
  this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2,
198
- usesEncryptedInternalMetadata(this.settings)
198
+ usesEncryptedInternalMetadata(this.settings),
199
+ this.options.acceptUnencryptedContent ?? false
199
200
  );
200
201
  }
201
202
  return Promise.resolve(true);
@@ -249,6 +250,7 @@ class DirectFileManipulator {
249
250
  handleFilenameCaseSensitive: this.options.handleFilenameCaseSensitive ?? DEFAULT_SETTINGS.handleFilenameCaseSensitive,
250
251
  usePathObfuscation: !!this.options.obfuscatePassphrase,
251
252
  encryptInternalMetadata: this.options.encryptInternalMetadata ?? false,
253
+ acceptUnencryptedContent: this.options.acceptUnencryptedContent ?? DEFAULT_SETTINGS.acceptUnencryptedContent,
252
254
  syncInternalFiles: this.options.syncInternalFiles ?? DEFAULT_SETTINGS.syncInternalFiles,
253
255
  E2EEAlgorithm: this.options.E2EEAlgorithm ?? E2EEAlgorithms.V2
254
256
  }
@@ -54,6 +54,7 @@ export declare function encodeSettingsToSetupURI(settingString: ObsidianLiveSync
54
54
  /** Generate a Setup URI for the current UTC window or in the existing persistent format. */
55
55
  export declare function encodeTimeBoundSetupURI(settingString: ObsidianLiveSyncSettings, passphrase: string, options?: TimeBoundSetupURIOptions): Promise<TimeBoundSetupURIResult>;
56
56
  export declare function decodeSettingsFromSetupURI(uri: string, passphrase: string): Promise<false | Omit<{
57
+ acceptUnencryptedContent: boolean;
57
58
  encryptInternalMetadata: boolean;
58
59
  idDerivationVersion: 0 | 1;
59
60
  idDerivationKey: string;
@@ -11,6 +11,7 @@ import { decryptString, encryptString } from "../encryption/stringEncryption.js"
11
11
  import { LOG_LEVEL_VERBOSE, Logger } from "octagonal-wheels/common/logger";
12
12
  import { configuredIdKey } from "../common/idDerivation.js";
13
13
  import { assertSupportedPathNormalizationVersion, getPathNormalizationVersion } from "../common/pathNormalization.js";
14
+ import { normaliseAcceptUnencryptedContent } from "../common/models/setting.encryption.js";
14
15
  function encodeSettingsToQRCodeData(settings) {
15
16
  settings = omitP2PRuntimeSettings(settings);
16
17
  configuredIdKey(settings);
@@ -54,6 +55,7 @@ function decodeSettingsFromQRCodeData(qr) {
54
55
  LOG_LEVEL_VERBOSE
55
56
  );
56
57
  }
58
+ newSettings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(newSettings.acceptUnencryptedContent);
57
59
  configuredIdKey(newSettings);
58
60
  newSettings.pathNormalizationVersion = getPathNormalizationVersion(newSettings);
59
61
  return omitP2PRuntimeSettings(newSettings);
@@ -213,6 +215,7 @@ async function decodeSettingsFromSetupURI(uri, passphrase) {
213
215
  const imported = JSON.parse(decrypted);
214
216
  const settings = {
215
217
  ...imported,
218
+ acceptUnencryptedContent: normaliseAcceptUnencryptedContent(imported.acceptUnencryptedContent),
216
219
  encryptInternalMetadata: typeof imported.encryptInternalMetadata === "boolean" ? imported.encryptInternalMetadata : false,
217
220
  idDerivationVersion: imported.idDerivationVersion ?? 0,
218
221
  idDerivationKey: imported.idDerivationKey ?? "",
@@ -57,6 +57,7 @@ const SETTINGS_SCHEMA_DEFAULTS = {
57
57
  periodicReplicationInterval: 60,
58
58
  syncOnFileOpen: false,
59
59
  encrypt: false,
60
+ acceptUnencryptedContent: false,
60
61
  passphrase: "",
61
62
  idDerivationVersion: 0,
62
63
  idDerivationKey: "",
@@ -185,7 +185,8 @@ const KeyIndexOfSettings = {
185
185
  pathNormalizationVersion: 168,
186
186
  batchSaveInLiveSync: 169,
187
187
  useCouchDBCacheControlHeadersOnly: 170,
188
- encryptedIdDerivationKey: -1
188
+ encryptedIdDerivationKey: -1,
189
+ acceptUnencryptedContent: 171
189
190
  };
190
191
  export {
191
192
  KeyIndexOfSettings
@@ -0,0 +1,2 @@
1
+ /** Return the explicit opt-in; absent and non-boolean values remain disabled. */
2
+ export declare function normaliseAcceptUnencryptedContent(value: unknown): boolean;
@@ -0,0 +1,6 @@
1
+ function normaliseAcceptUnencryptedContent(value) {
2
+ return value === true;
3
+ }
4
+ export {
5
+ normaliseAcceptUnencryptedContent
6
+ };
@@ -5,6 +5,7 @@ import {
5
5
  SETTING_VERSION_SUPPORT_CASE_INSENSITIVE
6
6
  } from "./setting.const.js";
7
7
  import { omitP2PRuntimeSettings } from "./setting.p2p.js";
8
+ import { normaliseAcceptUnencryptedContent } from "./setting.encryption.js";
8
9
  const SettingsMigrationReviewCodes = {
9
10
  LegacyUpdatePending: "legacy-update-review-pending",
10
11
  FutureSchema: "settings-schema-newer-than-runtime",
@@ -73,8 +74,10 @@ function prepareSettingsForLoad(storedSettings) {
73
74
  toVersion: CURRENT_SETTING_VERSION
74
75
  }
75
76
  ];
77
+ const settings = cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS);
78
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(source.acceptUnencryptedContent);
76
79
  return {
77
- settings: cloneSettings(source, SETTINGS_SCHEMA_DEFAULTS),
80
+ settings,
78
81
  sourceVersion,
79
82
  targetVersion: sourceVersion,
80
83
  isNewVault: false,
@@ -108,13 +111,15 @@ function prepareSettingsForLoad(storedSettings) {
108
111
  if (normalisedFilenameCase) migrated = { ...migrated, handleFilenameCaseSensitive: false };
109
112
  const normalisedInternalMetadata = typeof migrated.encryptInternalMetadata !== "boolean";
110
113
  if (normalisedInternalMetadata) migrated = { ...migrated, encryptInternalMetadata: false };
114
+ const normalisedAcceptUnencryptedContent = typeof migrated.acceptUnencryptedContent !== "boolean";
115
+ if (normalisedAcceptUnencryptedContent) migrated = { ...migrated, acceptUnencryptedContent: false };
111
116
  return {
112
117
  settings: cloneSettings(migrated, SETTINGS_SCHEMA_DEFAULTS),
113
118
  sourceVersion,
114
119
  targetVersion,
115
120
  isNewVault: false,
116
121
  isFromFutureSchema: false,
117
- changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata,
122
+ changed: sourceVersion !== targetVersion || normalisedConfiguredState || normalisedFilenameCase || normalisedInternalMetadata || normalisedAcceptUnencryptedContent,
118
123
  requiresSyncReview: reviewReasons.length > 0,
119
124
  reviewReasons
120
125
  };
@@ -489,6 +489,10 @@ export declare const SETTINGS_PROPERTY_POLICY: {
489
489
  readonly markdown: "include";
490
490
  readonly persistence: "include";
491
491
  };
492
+ readonly acceptUnencryptedContent: {
493
+ readonly markdown: "include";
494
+ readonly persistence: "include";
495
+ };
492
496
  readonly passphrase: {
493
497
  readonly markdown: "credentials";
494
498
  readonly persistence: "passphrase";
@@ -1,4 +1,5 @@
1
1
  import { DEFAULT_SETTINGS } from "./setting.const.defaults.js";
2
+ import { normaliseAcceptUnencryptedContent } from "./setting.encryption.js";
2
3
  const SettingPolicies = {
3
4
  Default: { markdown: "include", persistence: "include" },
4
5
  LocalOnly: { markdown: "omit", persistence: "include" },
@@ -123,6 +124,7 @@ const SETTINGS_PROPERTY_POLICY = {
123
124
  forcePathStyle: SettingPolicies.Default,
124
125
  remoteType: SettingPolicies.Default,
125
126
  encrypt: SettingPolicies.Default,
127
+ acceptUnencryptedContent: SettingPolicies.Default,
126
128
  passphrase: SettingPolicies.E2EEPassphrase,
127
129
  idDerivationVersion: SettingPolicies.MarkdownCredentials,
128
130
  pathNormalizationVersion: SettingPolicies.MarkdownCredentials,
@@ -230,6 +232,9 @@ function createMarkdownSettings(settings, includeCredentials = settings.writeCre
230
232
  copySetting(output, settings, key);
231
233
  }
232
234
  if (output.remoteConfigurations) output.remoteConfigurations = cloneProfiles(output);
235
+ if ("acceptUnencryptedContent" in output) {
236
+ output.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(output.acceptUnencryptedContent);
237
+ }
233
238
  return output;
234
239
  }
235
240
  function mergeMarkdownSettings(incoming, current) {
@@ -241,6 +246,9 @@ function mergeMarkdownSettings(incoming, current) {
241
246
  }
242
247
  }
243
248
  merged.remoteConfigurations = cloneProfiles(merged);
249
+ merged.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(
250
+ Object.prototype.hasOwnProperty.call(incoming, "acceptUnencryptedContent") ? incoming.acceptUnencryptedContent : current.acceptUnencryptedContent
251
+ );
244
252
  return merged;
245
253
  }
246
254
  function selectConnectionSettings(settings) {
@@ -271,6 +279,7 @@ function requireConfigurationCiphertext(value) {
271
279
  return value;
272
280
  }
273
281
  function prepareSettingsForPersistence(settings) {
282
+ settings.acceptUnencryptedContent = normaliseAcceptUnencryptedContent(settings.acceptUnencryptedContent);
274
283
  if (hasConnectionSettings(settings)) throw new Error("Connection settings were not prepared for persistence.");
275
284
  if (settings.encrypt && settings.passphrase !== "")
276
285
  throw new Error("The passphrase was not prepared for persistence.");
@@ -598,6 +598,8 @@ export interface EncryptionSettings {
598
598
  * Indicates whether E2EE is enabled.
599
599
  */
600
600
  encrypt: boolean;
601
+ /** Accept plaintext file content from the remote while E2EE is enabled. */
602
+ acceptUnencryptedContent: boolean;
601
603
  /**
602
604
  * The passphrase used for E2EE.
603
605
  */
@@ -20,6 +20,11 @@ const configurationNames = {
20
20
  name: "Encrypt internal file Properties",
21
21
  desc: "Encrypt file properties (paths, times, sizes, and Chunk references) used by Hidden File Sync and Customisation Sync. This affects future writes; manually rebuild the remote database to protect existing properties. Requires E2EE V2, Property Encryption, and compatible clients on every device."
22
22
  },
23
+ acceptUnencryptedContent: {
24
+ name: "Accept unencrypted content",
25
+ desc: "When E2EE is enabled, accept unencrypted content written by third-party tools which do not use the E2EE passphrase. Anyone with write access to the database can inject plaintext. Content sent by this plug-in remains encrypted.",
26
+ isAdvanced: true
27
+ },
23
28
  enableCompression: {
24
29
  name: "Data Compression",
25
30
  level: LEVEL_ADVANCED
@@ -249,6 +249,7 @@ export declare const TweakValuesTemplate: {
249
249
  bucketPrefix?: string;
250
250
  forcePathStyle?: boolean;
251
251
  remoteType?: import("./setting.type.js").RemoteType;
252
+ acceptUnencryptedContent?: boolean;
252
253
  passphrase?: string;
253
254
  idDerivationKey?: string;
254
255
  doNotUseFixedRevisionForChunks?: boolean;
@@ -139,6 +139,7 @@ export declare const AllSettingDefault: {
139
139
  remoteType: import("./types.js").RemoteType;
140
140
  pathNormalizationVersion: import("./models/setting.type.js").PathNormalizationVersion;
141
141
  encrypt: boolean;
142
+ acceptUnencryptedContent: boolean;
142
143
  passphrase: string;
143
144
  idDerivationVersion: 0 | 1;
144
145
  idDerivationKey: string;
@@ -3,11 +3,11 @@ import { isPlainText } from "../string_and_binary/path.js";
3
3
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
4
4
  import { arrayBufferToBase64Single, decodeBinary, writeString } from "../string_and_binary/convert.js";
5
5
  import {
6
- PREFIX_ENCRYPTED_CHUNK,
7
- PREFIX_OBFUSCATED,
6
+ IDPrefixes,
8
7
  SYNCINFO_ID
9
8
  } from "./types.js";
10
9
  import { normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes } from "./models/setting.p2p.js";
10
+ import { normaliseAcceptUnencryptedContent } from "./models/setting.encryption.js";
11
11
  import { isErrorOfMissingDoc } from "../pouchdb/utils_couchdb.js";
12
12
  import { joinDelimitedList, replaceAll, replaceAllPairs, splitDelimitedList } from "octagonal-wheels/string";
13
13
  import { formatDuration } from "octagonal-wheels/notation/duration";
@@ -94,13 +94,13 @@ async function isDocContentSame(docA, docB) {
94
94
  return isBlobContentEqual(blob1, blob2, isArrayBufferContentEqual);
95
95
  }
96
96
  function isObfuscatedEntry(doc) {
97
- if (doc._id.startsWith(PREFIX_OBFUSCATED)) {
97
+ if (doc._id.startsWith(IDPrefixes.Obfuscated)) {
98
98
  return true;
99
99
  }
100
100
  return false;
101
101
  }
102
102
  function isEncryptedChunkEntry(doc) {
103
- if (doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) {
103
+ if (doc._id.startsWith(IDPrefixes.EncryptedChunk)) {
104
104
  return true;
105
105
  }
106
106
  return false;
@@ -418,6 +418,7 @@ function pickEncryptionSettings(setting) {
418
418
  passphrase: setting.passphrase,
419
419
  usePathObfuscation: setting.usePathObfuscation,
420
420
  encryptInternalMetadata: setting.encryptInternalMetadata,
421
+ acceptUnencryptedContent: normaliseAcceptUnencryptedContent(setting.acceptUnencryptedContent),
421
422
  idDerivationVersion: setting.idDerivationVersion,
422
423
  idDerivationKey: setting.idDerivationKey
423
424
  };
@@ -1,6 +1,7 @@
1
1
  import { DOCID_SYNC_PARAMETERS } from "../common/types.js";
2
2
  import { isObfuscatedEntry, parseHeaderValues } from "../common/utils.js";
3
3
  import { getConfiguredFunctionsForEncryption, isEncryptedMeta } from "../pouchdb/encryption.js";
4
+ import { isUnencryptedContentRejectedError } from "../replication/UnencryptedContentRejectedError.js";
4
5
  import { isPathProbablyObfuscated } from "octagonal-wheels/encryption/encryption";
5
6
  import { decompressDoc } from "../pouchdb/compress.js";
6
7
  import { AuthorizationHeaderGenerator, generateCredentialObject } from "../replication/httplib.js";
@@ -76,7 +77,8 @@ function createCouchDBDiagnosticSource({
76
77
  settings.E2EEAlgorithm,
77
78
  false,
78
79
  () => {
79
- }
80
+ },
81
+ settings.acceptUnencryptedContent
80
82
  ).outgoing : async (doc) => doc;
81
83
  const decode = async (id, value) => {
82
84
  if (!value || typeof value !== "object" || !("_id" in value) || value._id !== id || !("_rev" in value) || typeof value._rev !== "string") {
@@ -157,7 +159,7 @@ function createCouchDBDiagnosticSource({
157
159
  checkCancelled();
158
160
  return {
159
161
  id,
160
- error: error instanceof DiagnosticReadError ? error : new DiagnosticReadError("document-unreadable")
162
+ error: error instanceof DiagnosticReadError || isUnencryptedContentRejectedError(error) ? error : new DiagnosticReadError("document-unreadable")
161
163
  };
162
164
  }
163
165
  })
@@ -1,6 +1,7 @@
1
1
  import type { FilePath, FilePathWithPrefix, UXDataWriteOptions, UXFileInfo, UXFileInfoStub, UXFolderInfo, UXStat } from "../common/types.js";
2
2
  import type { CustomRegExp } from "../common/utils.js";
3
3
  import type { FileWithFileStat, FileWithStatAsProp } from "../common/models/fileaccess.type.js";
4
+ import type { FileNameLookup } from "../platform/FilePathIndex.js";
4
5
  export interface IStorageAccessManager {
5
6
  processWriteFile<T>(file: UXFileInfoStub | FilePathWithPrefix, proc: () => Promise<T>): Promise<T>;
6
7
  processReadFile<T>(file: UXFileInfoStub | FilePathWithPrefix, proc: () => Promise<T>): Promise<T>;
@@ -9,7 +10,13 @@ export interface IStorageAccessManager {
9
10
  touch(file: FileWithStatAsProp | FileWithFileStat): void;
10
11
  clearTouched(): void;
11
12
  }
12
- export interface StorageAccess {
13
+ /**
14
+ * Storage facade with the shared name-query contract available on every host.
15
+ *
16
+ * An adapter can omit its indexed lookup capability; the service facade supplies
17
+ * the base fallback while retaining the FileNameLookup method contract.
18
+ */
19
+ export interface StorageAccess extends FileNameLookup {
13
20
  normalisePath(path: string): string;
14
21
  restoreState(): Promise<void>;
15
22
  /** Includes queued, running, and failed work; absence requires a conservative content check. */
@@ -36,7 +43,6 @@ export interface StorageAccess {
36
43
  readStubContent(stub: UXFileInfoStub): Promise<UXFileInfo | false>;
37
44
  getStub(path: string): Promise<UXFileInfoStub | UXFolderInfo | null>;
38
45
  getFiles(): Promise<UXFileInfoStub[]>;
39
- getFileNames(): Promise<FilePathWithPrefix[]>;
40
46
  touched(file: UXFileInfoStub | FilePathWithPrefix): Promise<void>;
41
47
  recentlyTouched(file: UXFileInfoStub | FilePathWithPrefix): Promise<boolean>;
42
48
  clearTouched(): void;
@@ -1,6 +1,11 @@
1
+ import { getUnencryptedContentRejectionMessage } from "../replication/unencryptedContentMessages.js";
2
+ import {
3
+ getUnencryptedContentRejection,
4
+ isUnencryptedContentRejectedError
5
+ } from "../replication/UnencryptedContentRejectedError.js";
1
6
  import { delay, promiseWithResolvers } from "octagonal-wheels/promises";
2
7
  import { unique } from "octagonal-wheels/collection";
3
- import { LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
8
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
4
9
  import { DEFAULT_SETTINGS } from "../common/types.js";
5
10
  import {} from "./ChunkManager.js";
6
11
  import { compatGlobal } from "../common/coreEnvFunctions.js";
@@ -251,7 +256,11 @@ class ChunkFetcher {
251
256
  LOG_LEVEL_VERBOSE
252
257
  );
253
258
  for (const chunk of invalidChunks) {
254
- Logger(`Invalid chunk: ${JSON.stringify(chunk)}`, LOG_LEVEL_VERBOSE);
259
+ const id = typeof chunk === "object" && chunk !== null && "_id" in chunk && typeof chunk._id === "string" ? chunk._id : void 0;
260
+ Logger(
261
+ id === void 0 ? "Invalid chunk without a string document ID." : `Invalid chunk document: ${JSON.stringify(id)}`,
262
+ LOG_LEVEL_VERBOSE
263
+ );
255
264
  }
256
265
  }
257
266
  if (chunks.length === 0) {
@@ -397,8 +406,22 @@ class ChunkFetcher {
397
406
  }
398
407
  this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);
399
408
  } catch (error) {
400
- Logger("An error occurred while fetching remote chunks.", LOG_LEVEL_VERBOSE);
401
- Logger(error, LOG_LEVEL_VERBOSE);
409
+ if (isUnencryptedContentRejectedError(error)) {
410
+ Logger(
411
+ getUnencryptedContentRejectionMessage("on-demand"),
412
+ LOG_LEVEL_NOTICE,
413
+ "unencrypted-content-rejected"
414
+ );
415
+ const rejection = getUnencryptedContentRejection(error);
416
+ const identifiers = rejection ? [rejection.documentId] : requestIDs;
417
+ Logger(
418
+ `On-demand retrieval rejected unencrypted content: ${identifiers.join(", ")}`,
419
+ LOG_LEVEL_VERBOSE
420
+ );
421
+ } else {
422
+ Logger("An error occurred while fetching remote chunks.", LOG_LEVEL_VERBOSE);
423
+ Logger(error, LOG_LEVEL_VERBOSE);
424
+ }
402
425
  } finally {
403
426
  for (const [id, pending] of requestClaims) {
404
427
  if (pending.inFlight) this.settleClaim(id, pending);
@@ -17,7 +17,7 @@ function decideMissingChunkAction({
17
17
  }
18
18
  function isValidChunk(chunk) {
19
19
  const candidate = chunk;
20
- return !!candidate && typeof candidate._id === "string" && typeof candidate.data === "string";
20
+ return !!candidate && candidate.type === "leaf" && typeof candidate._id === "string" && !candidate._id.startsWith("_local/") && typeof candidate.data === "string";
21
21
  }
22
22
  function classifyFetchedChunks(requestedIds, fetched) {
23
23
  const chunks = [];
@@ -0,0 +1,110 @@
1
+ import type { FilePath, PathComparisonSettings } from "./pathTypes.js";
2
+ /**
3
+ * Original file paths removed and added by one synchronous membership change.
4
+ *
5
+ * @remarks
6
+ * Repeated additions and absent removals are harmless. A path present in both
7
+ * lists remains present, including when it was absent before the change.
8
+ * Hosts expand folder renames into file-path deltas before applying them.
9
+ */
10
+ export interface FilePathDelta {
11
+ readonly removed: readonly FilePath[];
12
+ readonly added: readonly FilePath[];
13
+ }
14
+ /** Controls whether a name read can reuse the host's maintained inventory. */
15
+ export interface FileNameReadOptions {
16
+ /**
17
+ * Ask the host's listing authority again instead of reusing the name index.
18
+ *
19
+ * @remarks
20
+ * Freshness follows that host's existing listing contract. For example,
21
+ * Obsidian supplies its Vault listing rather than an independent disk walk.
22
+ */
23
+ readonly fresh?: boolean;
24
+ }
25
+ /** Host-owned name reads and candidate selection for one storage root. */
26
+ export interface FileNameLookup {
27
+ /**
28
+ * Read the host's supported original file paths.
29
+ *
30
+ * @param options - Whether to ask the listing authority for a fresh view.
31
+ * @returns A copy of the complete supported inventory, preserving spelling.
32
+ * @throws Rejects unavailable or failed inventory reads rather than reporting
33
+ * a successful empty inventory. Host-specific listing exclusions still apply.
34
+ */
35
+ getFileNames(options?: FileNameReadOptions): Promise<FilePath[]>;
36
+ /**
37
+ * Find original paths which match the requested path-identity comparison key.
38
+ *
39
+ * @param path - Original file path to compare within this storage root.
40
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
41
+ * @returns Every matching original path in diagnostic order, including the
42
+ * requested spelling when present. An empty result means no supported match.
43
+ * @throws Rejects unavailable coverage and host validation or read failures.
44
+ * @remarks
45
+ * The host establishes read readiness and physical-path safety. The caller
46
+ * decides whether multiple candidates constitute a collision; this operation
47
+ * neither chooses a preferred spelling nor compares file contents.
48
+ */
49
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]>;
50
+ }
51
+ /**
52
+ * Maintains original file-path membership and lazily materialised identity buckets.
53
+ *
54
+ * @remarks
55
+ * The host owns supported-path validation, observation, and query readiness.
56
+ * This class stores original spellings and performs no I/O. Membership changes
57
+ * update every materialised policy map; at most four policy maps are retained.
58
+ * Queries return copies and leave file contents and physical names untouched.
59
+ *
60
+ * A first query for a policy derives its buckets in one pass over the retained
61
+ * paths. Subsequent queries select and sort only the matching candidates.
62
+ */
63
+ export declare class FilePathIndex {
64
+ private paths;
65
+ private indexes;
66
+ /**
67
+ * Replace the complete inventory and all materialised policy maps together.
68
+ *
69
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
70
+ * into one membership without normalising their spelling.
71
+ * @throws Propagates invalid runtime members or iterable failures before
72
+ * replacing the current inventory or any existing policy map.
73
+ * @remarks
74
+ * Validation checks string members; filesystem admission remains the host's
75
+ * responsibility. Callers use this after a successful initial or fresh read.
76
+ */
77
+ replaceAll(paths: Iterable<FilePath>): void;
78
+ /**
79
+ * Apply one membership delta to the inventory and every cached policy map.
80
+ *
81
+ * @param delta - Original paths removed and added by the same change.
82
+ * @throws Propagates invalid runtime members before changing retained state.
83
+ * @remarks
84
+ * Inputs and comparison keys are prepared before mutation. The synchronous
85
+ * update publishes no intermediate rename state. Repeated notifications do
86
+ * not create duplicate memberships, and content-only edits need no delta.
87
+ */
88
+ apply(delta: FilePathDelta): void;
89
+ /**
90
+ * Copy the current in-memory membership without refreshing the host listing.
91
+ *
92
+ * @returns Original spellings in an independent array. Full-list ordering is
93
+ * unspecified; changing the returned array cannot change this index.
94
+ */
95
+ getFileNames(): FilePath[];
96
+ /**
97
+ * Select every indexed path with the requested storage comparison key.
98
+ *
99
+ * @param path - Path whose identity selects a candidate bucket.
100
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
101
+ * @returns A sorted copy of all matching original paths, or an empty array
102
+ * when no indexed path matches. Multiple paths remain separate candidates.
103
+ * @throws Rejects a non-string path or unsupported comparison settings.
104
+ * @remarks
105
+ * The first query for each policy materialises its buckets. Later membership
106
+ * deltas maintain those buckets incrementally. Host readiness, existence,
107
+ * physical alias checks, and the final collision decision are external.
108
+ */
109
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): readonly FilePath[];
110
+ }