@vrtmrz/livesync-commonlib 0.4.2 → 0.4.3

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 (45) 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/managers/ChunkFetcher.js +27 -4
  20. package/dist/managers/chunkFetcher.helper.js +1 -1
  21. package/dist/pouchdb/StreamingFetch.d.ts +1 -2
  22. package/dist/pouchdb/encryption.d.ts +5 -10
  23. package/dist/pouchdb/encryption.eden.d.ts +11 -0
  24. package/dist/pouchdb/encryption.eden.js +37 -0
  25. package/dist/pouchdb/encryption.js +67 -63
  26. package/dist/pouchdb/encryption.policy.d.ts +9 -0
  27. package/dist/pouchdb/encryption.policy.js +125 -0
  28. package/dist/replication/UnencryptedContentRejectedError.d.ts +16 -0
  29. package/dist/replication/UnencryptedContentRejectedError.js +44 -0
  30. package/dist/replication/couchdb/LiveSyncReplicator.js +41 -4
  31. package/dist/replication/index.d.ts +2 -0
  32. package/dist/replication/index.js +3 -0
  33. package/dist/replication/trystero/TrysteroReplicator.d.ts +2 -0
  34. package/dist/replication/unencryptedContentMessages.d.ts +8 -0
  35. package/dist/replication/unencryptedContentMessages.js +12 -0
  36. package/dist/serviceModules/Rebuilder.js +28 -4
  37. package/dist/services/base/RemoteConnection.d.ts +2 -0
  38. package/dist/services/base/RemoteService.js +2 -1
  39. package/dist/services/base/SettingService.js +2 -0
  40. package/dist/settings.d.ts +2 -1
  41. package/dist/settings.js +2 -0
  42. package/dist/worker/bgWorker.js +1 -1
  43. package/docs/offline-scanner.md +2 -1
  44. package/docs/settings-lifecycle.md +4 -0
  45. package/package.json +1 -1
@@ -4,17 +4,39 @@ import {
4
4
  isMetaEntry
5
5
  } from "../common/types.js";
6
6
  import { isEncryptedChunkEntry, isSyncInfoEntry, isObfuscatedEntry } from "../common/utils.js";
7
- import { isPathProbablyObfuscated, obfuscatePath } from "octagonal-wheels/encryption/encryption";
7
+ import { normaliseAcceptUnencryptedContent } from "../common/models/setting.encryption.js";
8
+ import { ENCRYPT_V2_PREFIX, isPathProbablyObfuscated, obfuscatePath } from "octagonal-wheels/encryption/encryption";
8
9
  import { getPath } from "../string_and_binary/path.js";
9
10
  import { ICHeader, ICXHeader, PSCHeader } from "../common/models/fileaccess.const.js";
10
- import { PREFIX_OBFUSCATED } from "../common/types.js";
11
+ import { IDPrefixes } from "../common/types.js";
11
12
  import { encryptWorker, decryptWorker, encryptHKDFWorker, decryptHKDFWorker } from "#worker";
13
+ import {
14
+ assertUnencryptedContentPolicy,
15
+ hasForceV1CiphertextHeaderFor,
16
+ isEncryptedEntry
17
+ } from "./encryption.policy.js";
18
+ import {
19
+ EDEN_ENCRYPTED_KEY,
20
+ EDEN_ENCRYPTED_KEY_HKDF,
21
+ shouldEncryptEden,
22
+ shouldEncryptEdenHKDF,
23
+ shouldDecryptEden,
24
+ shouldDecryptEdenHKDF
25
+ } from "./encryption.eden.js";
26
+ import {
27
+ EDEN_ENCRYPTED_KEY as EDEN_ENCRYPTED_KEY2,
28
+ EDEN_ENCRYPTED_KEY_HKDF as EDEN_ENCRYPTED_KEY_HKDF2,
29
+ shouldEncryptEden as shouldEncryptEden2,
30
+ shouldEncryptEdenHKDF as shouldEncryptEdenHKDF2,
31
+ shouldDecryptEden as shouldDecryptEden2,
32
+ shouldDecryptEdenHKDF as shouldDecryptEdenHKDF2
33
+ } from "./encryption.eden.js";
12
34
  const encrypt = encryptWorker;
13
35
  const decrypt = decryptWorker;
14
36
  const encryptHKDF = encryptHKDFWorker;
15
37
  const decryptHKDF = decryptHKDFWorker;
16
38
  const Encrypt_HKDF_Header = "%=";
17
- const Encrypt_OLD_Header = "%";
39
+ const Encrypt_OLD_Header = ENCRYPT_V2_PREFIX;
18
40
  const EncryptionVersions = {
19
41
  UNENCRYPTED: 0,
20
42
  ENCRYPTED: 1,
@@ -37,10 +59,7 @@ async function tryDecryptV1AsFallback(encryptedData, passphrase, useDynamicItera
37
59
  return await decrypt(encryptedData, passphrase, useDynamicIterationCount);
38
60
  } catch (ex) {
39
61
  try {
40
- log(
41
- "Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",
42
- LOG_LEVEL_VERBOSE
43
- );
62
+ log("Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.", LOG_LEVEL_VERBOSE);
44
63
  log(ex, LOG_LEVEL_VERBOSE);
45
64
  return await decrypt(encryptedData, passphrase, false);
46
65
  } catch (ex2) {
@@ -55,9 +74,7 @@ function isEncryptedMeta(doc) {
55
74
  return "path" in doc && doc.path.startsWith(ENCRYPTED_META_PREFIX);
56
75
  }
57
76
  function isInternalObfuscatedEntry(doc) {
58
- return [ICHeader, ICXHeader, PSCHeader].some(
59
- (prefix) => doc._id.startsWith(`${prefix}${PREFIX_OBFUSCATED}`)
60
- );
77
+ return [ICHeader, ICXHeader, PSCHeader].some((prefix) => doc._id.startsWith(`${prefix}${IDPrefixes.Obfuscated}`));
61
78
  }
62
79
  async function encryptMetaWithHKDF(doc, passphrase, pbkdf2Salt) {
63
80
  if (isEncryptedMeta(doc)) {
@@ -153,10 +170,11 @@ async function incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, ge
153
170
  }
154
171
  return saveDoc;
155
172
  }
156
- async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt, log) {
173
+ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, getPBKDF2Salt, log, algorithm, acceptUnencryptedContent) {
157
174
  const loadDoc = {
158
175
  ...doc
159
176
  };
177
+ assertUnencryptedContentPolicy(loadDoc, algorithm, acceptUnencryptedContent);
160
178
  if (isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc)) {
161
179
  try {
162
180
  const encryptionVersion = getEncryptionVersion(loadDoc);
@@ -302,28 +320,30 @@ async function incomingEncryptV1(doc, passphrase, useDynamicIterationCount) {
302
320
  }
303
321
  return saveDoc;
304
322
  }
305
- async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, log) {
323
+ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, useDynamicIterationCount, log, acceptUnencryptedContent) {
306
324
  const loadDoc = {
307
325
  ...doc
308
326
  };
309
327
  const _isChunkOrSyncInfo = isEncryptedChunkEntry(loadDoc) || isSyncInfoEntry(loadDoc);
310
328
  const _isObfuscatedEntry = isObfuscatedEntry(loadDoc);
311
329
  const _shouldDecryptEden = shouldDecryptEden(loadDoc);
312
- if (_isChunkOrSyncInfo || _isObfuscatedEntry || _shouldDecryptEden) {
330
+ const hasMarkedCiphertext = "e_" in loadDoc && loadDoc.e_ === true;
331
+ const hasForceV1CiphertextHeader = _isChunkOrSyncInfo && !hasMarkedCiphertext && hasForceV1CiphertextHeaderFor(loadDoc.data);
332
+ assertUnencryptedContentPolicy(
333
+ loadDoc,
334
+ E2EEAlgorithms.ForceV1,
335
+ acceptUnencryptedContent,
336
+ hasForceV1CiphertextHeader
337
+ );
338
+ const _shouldDecryptData = isEncryptedEntry(loadDoc, hasForceV1CiphertextHeader);
339
+ if (_shouldDecryptData || _isObfuscatedEntry || _shouldDecryptEden) {
313
340
  if (migrationDecrypt && decrypted.has(loadDoc._id)) {
314
341
  return loadDoc;
315
342
  }
316
343
  try {
317
- if (_isChunkOrSyncInfo) {
344
+ if (_shouldDecryptData) {
318
345
  loadDoc.data = await decrypt(loadDoc.data, passphrase, useDynamicIterationCount);
319
- delete loadDoc.e_;
320
- } else if ("e_" in loadDoc) {
321
- loadDoc.data = await decrypt(
322
- loadDoc.data,
323
- passphrase,
324
- useDynamicIterationCount
325
- );
326
- delete loadDoc.e_;
346
+ if ("e_" in loadDoc) delete loadDoc.e_;
327
347
  }
328
348
  if (_isObfuscatedEntry) {
329
349
  const path = getPath(loadDoc);
@@ -346,7 +366,7 @@ async function outgoingDecryptV1(doc, migrationDecrypt, decrypted, passphrase, u
346
366
  } catch (ex) {
347
367
  if (useDynamicIterationCount) {
348
368
  try {
349
- if (_isChunkOrSyncInfo) {
369
+ if (_shouldDecryptData) {
350
370
  loadDoc.data = await decrypt(loadDoc.data, passphrase, false);
351
371
  }
352
372
  if (_isObfuscatedEntry) {
@@ -388,8 +408,9 @@ let preprocessOutgoing = async (doc) => {
388
408
  let preprocessIncoming = async (doc) => {
389
409
  return await Promise.resolve(doc);
390
410
  };
391
- function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, log = Logger) {
411
+ function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, log = Logger, acceptUnencryptedContent = false) {
392
412
  const decryptedCache = /* @__PURE__ */ new Map();
413
+ const acceptUnencrypted = normaliseAcceptUnencryptedContent(acceptUnencryptedContent);
393
414
  const incoming = (doc) => algorithm === E2EEAlgorithms.V2 ? incomingEncryptHKDF(doc, passphrase, useDynamicIterationCount, getPBKDF2Salt, encryptInternalMetadata) : incomingEncryptV1(doc, passphrase, useDynamicIterationCount);
394
415
  const outgoing = (doc) => algorithm !== E2EEAlgorithms.ForceV1 ? outgoingDecryptHKDF(
395
416
  doc,
@@ -398,21 +419,33 @@ function getConfiguredFunctionsForEncryption(passphrase, useDynamicIterationCoun
398
419
  passphrase,
399
420
  useDynamicIterationCount,
400
421
  getPBKDF2Salt,
401
- log
402
- ) : outgoingDecryptV1(doc, migrationDecrypt, decryptedCache, passphrase, useDynamicIterationCount, log);
422
+ log,
423
+ algorithm,
424
+ acceptUnencrypted
425
+ ) : outgoingDecryptV1(
426
+ doc,
427
+ migrationDecrypt,
428
+ decryptedCache,
429
+ passphrase,
430
+ useDynamicIterationCount,
431
+ log,
432
+ acceptUnencrypted
433
+ );
403
434
  return {
404
435
  incoming,
405
436
  outgoing
406
437
  };
407
438
  }
408
- const enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false) => {
439
+ const enableEncryption = (db, passphrase, useDynamicIterationCount, migrationDecrypt, getPBKDF2Salt, algorithm, encryptInternalMetadata = false, acceptUnencryptedContent = false) => {
409
440
  const { incoming, outgoing } = getConfiguredFunctionsForEncryption(
410
441
  passphrase,
411
442
  useDynamicIterationCount,
412
443
  migrationDecrypt,
413
444
  getPBKDF2Salt,
414
445
  algorithm,
415
- encryptInternalMetadata
446
+ encryptInternalMetadata,
447
+ Logger,
448
+ acceptUnencryptedContent
416
449
  );
417
450
  db.transform({
418
451
  incoming,
@@ -427,38 +460,9 @@ function disableEncryption() {
427
460
  return await Promise.resolve(doc);
428
461
  };
429
462
  }
430
- const EDEN_ENCRYPTED_KEY = "h:++encrypted";
431
- const EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
432
- function shouldEncryptEden(doc) {
433
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
434
- return true;
435
- }
436
- return false;
437
- }
438
- function shouldEncryptEdenHKDF(doc) {
439
- if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
440
- if (Object.keys(doc.eden).length === 0) {
441
- return false;
442
- }
443
- return true;
444
- }
445
- return false;
446
- }
447
- function shouldDecryptEden(doc) {
448
- if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
449
- return true;
450
- }
451
- return false;
452
- }
453
- function shouldDecryptEdenHKDF(doc) {
454
- if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
455
- return true;
456
- }
457
- return false;
458
- }
459
463
  export {
460
- EDEN_ENCRYPTED_KEY,
461
- EDEN_ENCRYPTED_KEY_HKDF,
464
+ EDEN_ENCRYPTED_KEY2 as EDEN_ENCRYPTED_KEY,
465
+ EDEN_ENCRYPTED_KEY_HKDF2 as EDEN_ENCRYPTED_KEY_HKDF,
462
466
  decrypt,
463
467
  decryptHKDF,
464
468
  disableEncryption,
@@ -469,8 +473,8 @@ export {
469
473
  isEncryptedMeta,
470
474
  preprocessIncoming,
471
475
  preprocessOutgoing,
472
- shouldDecryptEden,
473
- shouldDecryptEdenHKDF,
474
- shouldEncryptEden,
475
- shouldEncryptEdenHKDF
476
+ shouldDecryptEden2 as shouldDecryptEden,
477
+ shouldDecryptEdenHKDF2 as shouldDecryptEdenHKDF,
478
+ shouldEncryptEden2 as shouldEncryptEden,
479
+ shouldEncryptEdenHKDF2 as shouldEncryptEdenHKDF
476
480
  };
@@ -0,0 +1,9 @@
1
+ import { type AnyEntry, type EntryLeaf, type E2EEAlgorithm } from "../common/types.js";
2
+ export declare function hasForceV1CiphertextHeaderFor(data: unknown): boolean;
3
+ export declare function assertUnencryptedContentPolicy(doc: AnyEntry | EntryLeaf, algorithm: E2EEAlgorithm, acceptUnencryptedContent: boolean, hasForceV1CiphertextHeader?: boolean): void;
4
+ type EncryptedEntry = (AnyEntry | EntryLeaf) & {
5
+ data: string;
6
+ };
7
+ /** Identify a body handled by the V1 decryptor; authentication remains with the decryptor. */
8
+ export declare function isEncryptedEntry(doc: AnyEntry | EntryLeaf, hasForceV1CiphertextHeader: boolean): doc is EncryptedEntry;
9
+ export {};
@@ -0,0 +1,125 @@
1
+ import {
2
+ E2EEAlgorithms,
3
+ EntryTypes,
4
+ DOCID_SYNC_PARAMETERS,
5
+ MILESTONE_DOCID,
6
+ NODEINFO_DOCID,
7
+ SYNCINFO_ID,
8
+ VERSIONING_DOCID,
9
+ IDPrefixes
10
+ } from "../common/types.js";
11
+ import { isEncryptedChunkEntry, isSyncInfoEntry, isObfuscatedEntry } from "../common/utils.js";
12
+ import {
13
+ UnencryptedContentRejectedError
14
+ } from "../replication/UnencryptedContentRejectedError.js";
15
+ import {
16
+ ENCRYPT_V1_PREFIX_PROBABLY,
17
+ ENCRYPT_V2_PREFIX,
18
+ ENCRYPT_V3_PREFIX
19
+ } from "octagonal-wheels/encryption/encryption";
20
+ import { EDEN_ENCRYPTED_KEY, EDEN_ENCRYPTED_KEY_HKDF, shouldDecryptEden } from "./encryption.eden.js";
21
+ const METADATA_ONLY_ENTRY_TYPES = /* @__PURE__ */ new Set([
22
+ EntryTypes.NOTE_BINARY,
23
+ EntryTypes.NOTE_PLAIN,
24
+ EntryTypes.INTERNAL_FILE
25
+ ]);
26
+ const ENCRYPTED_EDEN_KEYS = /* @__PURE__ */ new Set([EDEN_ENCRYPTED_KEY, EDEN_ENCRYPTED_KEY_HKDF]);
27
+ const CONTROL_DOCUMENT_TYPES = /* @__PURE__ */ new Map([
28
+ [DOCID_SYNC_PARAMETERS, EntryTypes.SYNC_PARAMETERS],
29
+ [MILESTONE_DOCID, EntryTypes.MILESTONE_INFO],
30
+ [NODEINFO_DOCID, EntryTypes.NODE_INFO],
31
+ [SYNCINFO_ID, EntryTypes.SYNC_INFO],
32
+ [VERSIONING_DOCID, EntryTypes.VERSION_INFO]
33
+ ]);
34
+ function hasReadableBody(value) {
35
+ return value !== void 0;
36
+ }
37
+ function isEncryptedEdenKey(key, algorithm) {
38
+ return key === EDEN_ENCRYPTED_KEY || key === EDEN_ENCRYPTED_KEY_HKDF && algorithm !== E2EEAlgorithms.ForceV1;
39
+ }
40
+ function hasPlaintextEden(record, algorithm) {
41
+ const eden = record.eden;
42
+ if (typeof eden !== "object" || eden === null) return false;
43
+ const keys = Object.keys(eden);
44
+ return keys.some((key) => !isEncryptedEdenKey(key, algorithm));
45
+ }
46
+ function hasUnsupportedEncryptedEden(record, algorithm) {
47
+ const eden = record.eden;
48
+ if (typeof eden !== "object" || eden === null) return false;
49
+ return Object.keys(eden).some(
50
+ (key) => ENCRYPTED_EDEN_KEYS.has(key) && !isEncryptedEdenKey(key, algorithm)
51
+ );
52
+ }
53
+ function getUnencryptedContentKinds(doc, algorithm) {
54
+ const record = doc;
55
+ const documentId = typeof record._id === "string" ? record._id : "";
56
+ const type = record.type;
57
+ if (record._deleted === true || documentId.startsWith("_local/")) return [];
58
+ const isChunkId = documentId.startsWith(IDPrefixes.Chunk);
59
+ const expectedControlType = CONTROL_DOCUMENT_TYPES.get(documentId);
60
+ const isControlDocument = expectedControlType !== void 0 && expectedControlType === type;
61
+ if (!isChunkId && isControlDocument) return [];
62
+ const isChunkBody = isChunkId || type === EntryTypes.CHUNK || type === EntryTypes.CHUNK_PACK;
63
+ if (!isChunkBody && METADATA_ONLY_ENTRY_TYPES.has(type) && record.deleted === true) return [];
64
+ const kinds = [];
65
+ if (hasPlaintextEden(record, algorithm)) kinds.push("eden");
66
+ if (hasReadableBody(record.data)) kinds.push(isChunkBody ? "chunk" : "inline-note");
67
+ return kinds;
68
+ }
69
+ function isBase64Payload(value) {
70
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
71
+ }
72
+ function hasForceV1CiphertextHeaderFor(data) {
73
+ if (typeof data !== "string") return false;
74
+ if (data.startsWith(ENCRYPT_V3_PREFIX)) {
75
+ return /^[0-9a-f]{24}$/i.test(data.slice(2, 26)) && isBase64Payload(data.slice(26));
76
+ }
77
+ if (data.startsWith(ENCRYPT_V2_PREFIX)) {
78
+ return /^[0-9a-f]{64}$/i.test(data.slice(1, 65)) && isBase64Payload(data.slice(65));
79
+ }
80
+ if (!data.startsWith(ENCRYPT_V1_PREFIX_PROBABLY) || !data.endsWith("]")) return false;
81
+ try {
82
+ const parsed = JSON.parse(data);
83
+ if (!Array.isArray(parsed) || parsed.length !== 3 || !parsed.every((part) => typeof part === "string")) {
84
+ return false;
85
+ }
86
+ const [ciphertext, iv, salt] = parsed;
87
+ return isBase64Payload(ciphertext) && /^[0-9a-f]{32}$/i.test(iv) && /^[0-9a-f]{32}$/i.test(salt);
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+ function assertUnencryptedContentPolicy(doc, algorithm, acceptUnencryptedContent, hasForceV1CiphertextHeader = false) {
93
+ const contentKinds = getUnencryptedContentKinds(doc, algorithm);
94
+ if (contentKinds.length === 0) return;
95
+ const record = doc;
96
+ if (hasUnsupportedEncryptedEden(record, algorithm)) {
97
+ throw new Error("Encrypted Eden uses a representation which this E2EE reader cannot decrypt.");
98
+ }
99
+ const dataIsHandledByExistingDecryptor = isEncryptedChunkEntry(doc) || isSyncInfoEntry(doc);
100
+ const forceV1DecryptsMarkedData = algorithm === E2EEAlgorithms.ForceV1 && (dataIsHandledByExistingDecryptor || isObfuscatedEntry(doc) || shouldDecryptEden(doc));
101
+ for (const contentKind of contentKinds) {
102
+ if (contentKind !== "eden" && record.e_ === true) {
103
+ if (forceV1DecryptsMarkedData || dataIsHandledByExistingDecryptor) continue;
104
+ throw new Error("Encrypted file content uses a representation which this E2EE reader cannot decrypt.");
105
+ }
106
+ if (contentKind === "chunk" && algorithm === E2EEAlgorithms.ForceV1 && !record.e_ && isEncryptedChunkEntry(doc) && hasForceV1CiphertextHeader) {
107
+ continue;
108
+ }
109
+ if (!acceptUnencryptedContent) throw new UnencryptedContentRejectedError(doc._id, contentKind);
110
+ }
111
+ }
112
+ function isEncryptedEntry(doc, hasForceV1CiphertextHeader) {
113
+ const hasMarkedCiphertext = "e_" in doc && doc.e_ === true;
114
+ const shouldDecryptData = isEncryptedChunkEntry(doc) || isSyncInfoEntry(doc) ? hasMarkedCiphertext || hasForceV1CiphertextHeader : (isObfuscatedEntry(doc) || shouldDecryptEden(doc)) && hasMarkedCiphertext;
115
+ if (!shouldDecryptData) return false;
116
+ if (!("data" in doc) || typeof doc.data !== "string") {
117
+ throw new TypeError("Encrypted file content must be a string.");
118
+ }
119
+ return true;
120
+ }
121
+ export {
122
+ assertUnencryptedContentPolicy,
123
+ hasForceV1CiphertextHeaderFor,
124
+ isEncryptedEntry
125
+ };
@@ -0,0 +1,16 @@
1
+ import type { DocumentID } from "../common/types.js";
2
+ export type UnencryptedContentKind = "chunk" | "inline-note" | "eden";
3
+ export declare class UnencryptedContentRejectedError extends Error {
4
+ readonly documentId: DocumentID;
5
+ readonly contentKind: UnencryptedContentKind;
6
+ readonly name = "UnencryptedContentRejectedError";
7
+ readonly code = "UNENCRYPTED_CONTENT_REJECTED";
8
+ constructor(documentId: DocumentID, contentKind: UnencryptedContentKind);
9
+ }
10
+ /** Recognise the rejection through PouchDB-shaped errors and ordinary cause wrappers. */
11
+ export declare function isUnencryptedContentRejectedError(error: unknown): boolean;
12
+ /** Return only safe document diagnostics; never expose the rejected body or encryption key. */
13
+ export declare function getUnencryptedContentRejection(error: unknown): {
14
+ documentId: string;
15
+ contentKind: string;
16
+ } | undefined;
@@ -0,0 +1,44 @@
1
+ const UNENCRYPTED_CONTENT_REJECTED_CODE = "UNENCRYPTED_CONTENT_REJECTED";
2
+ const UNENCRYPTED_CONTENT_REJECTED_NAME = "UnencryptedContentRejectedError";
3
+ class UnencryptedContentRejectedError extends Error {
4
+ constructor(documentId, contentKind) {
5
+ super(`Unencrypted ${contentKind} content in remote document ${documentId} was rejected while E2EE is enabled.`);
6
+ this.documentId = documentId;
7
+ this.contentKind = contentKind;
8
+ }
9
+ documentId;
10
+ contentKind;
11
+ name = UNENCRYPTED_CONTENT_REJECTED_NAME;
12
+ code = UNENCRYPTED_CONTENT_REJECTED_CODE;
13
+ }
14
+ function inspectUnencryptedContentRejection(error) {
15
+ const seen = /* @__PURE__ */ new Set();
16
+ const pending = [error];
17
+ let details;
18
+ let rejected = false;
19
+ while (pending.length > 0) {
20
+ const current = pending.pop();
21
+ if (typeof current !== "object" || current === null || seen.has(current)) continue;
22
+ seen.add(current);
23
+ const candidate = current;
24
+ if (candidate.code === UNENCRYPTED_CONTENT_REJECTED_CODE || candidate.name === UNENCRYPTED_CONTENT_REJECTED_NAME) {
25
+ rejected = true;
26
+ if (typeof candidate.documentId === "string" && typeof candidate.contentKind === "string") {
27
+ details ??= { documentId: candidate.documentId, contentKind: candidate.contentKind };
28
+ }
29
+ }
30
+ if ("cause" in candidate) pending.push(candidate.cause);
31
+ }
32
+ return { rejected, details };
33
+ }
34
+ function isUnencryptedContentRejectedError(error) {
35
+ return inspectUnencryptedContentRejection(error).rejected;
36
+ }
37
+ function getUnencryptedContentRejection(error) {
38
+ return inspectUnencryptedContentRejection(error).details;
39
+ }
40
+ export {
41
+ UnencryptedContentRejectedError,
42
+ getUnencryptedContentRejection,
43
+ isUnencryptedContentRejectedError
44
+ };
@@ -1,3 +1,8 @@
1
+ import { getUnencryptedContentRejectionMessage } from "../unencryptedContentMessages.js";
2
+ import {
3
+ getUnencryptedContentRejection,
4
+ isUnencryptedContentRejectedError
5
+ } from "../UnencryptedContentRejectedError.js";
1
6
  import { observeReplicationProgress } from "./replicationProgress.js";
2
7
  import {
3
8
  VER,
@@ -93,6 +98,14 @@ async function* genReplication(s, signal) {
93
98
  void s.on("denied", (err) => push(["denied", err]));
94
99
  void s.on("error", (err) => push(["error", err]));
95
100
  void s.on("paused", (err) => push(["paused", err]));
101
+ const requestSource = s.pull ?? s;
102
+ let policyFailureReported = false;
103
+ const onRequestError = (error) => {
104
+ if (policyFailureReported || !isUnencryptedContentRejectedError(error)) return;
105
+ policyFailureReported = true;
106
+ push(["error", error]);
107
+ };
108
+ requestSource.addListener("requestError", onRequestError);
96
109
  void s.then(() => push(["finally"])).catch(() => push(["finally"]));
97
110
  const onAbort = () => inbox.close();
98
111
  signal.addEventListener("abort", onAbort, { once: true });
@@ -111,6 +124,7 @@ async function* genReplication(s, signal) {
111
124
  }
112
125
  } finally {
113
126
  signal.removeEventListener("abort", onAbort);
127
+ requestSource.removeListener("requestError", onRequestError);
114
128
  s.cancel();
115
129
  inbox.close();
116
130
  }
@@ -166,6 +180,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
166
180
  value.encrypt,
167
181
  value.passphrase,
168
182
  value.E2EEAlgorithm,
183
+ value.encrypt === true && value.acceptUnencryptedContent === true,
169
184
  value.enableCompression,
170
185
  value.pathNormalizationVersion,
171
186
  value.readChunksOnline,
@@ -190,10 +205,15 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
190
205
  return void 0;
191
206
  }
192
207
  connection = openedConnection;
193
- return await prepareInitialFetchFastForward(local, connection.db, {
194
- push: {},
195
- ...snapshot.readChunksOnline ? { pull: { ...selectorOnDemandPull } } : {}
196
- }, isCurrent);
208
+ return await prepareInitialFetchFastForward(
209
+ local,
210
+ connection.db,
211
+ {
212
+ push: {},
213
+ ...snapshot.readChunksOnline ? { pull: { ...selectorOnDemandPull } } : {}
214
+ },
215
+ isCurrent
216
+ );
197
217
  },
198
218
  dispose: async () => {
199
219
  if (disposed) return;
@@ -359,6 +379,17 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
359
379
  this.syncStatus = "ERRORED";
360
380
  this.abortController();
361
381
  this.updateInfo();
382
+ if (isUnencryptedContentRejectedError(e)) {
383
+ Logger(getUnencryptedContentRejectionMessage("replication"), LOG_LEVEL_NOTICE, "sync");
384
+ const rejection = getUnencryptedContentRejection(e);
385
+ if (rejection) {
386
+ Logger(
387
+ `CouchDB replication rejected ${rejection.contentKind}: ${rejection.documentId}`,
388
+ LOG_LEVEL_VERBOSE
389
+ );
390
+ }
391
+ return;
392
+ }
362
393
  Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
363
394
  Logger(e, LOG_LEVEL_VERBOSE);
364
395
  }
@@ -440,6 +471,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
440
471
  return "FAILED";
441
472
  case "error":
442
473
  this.replicationErrored(e);
474
+ if (isUnencryptedContentRejectedError(e)) return "FAILED";
443
475
  Logger("Replication stopped.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
444
476
  if (this.env.services.remote.hadLastPostFailedBySize) {
445
477
  if (e && e.status == 413) {
@@ -469,6 +501,10 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
469
501
  }
470
502
  return "CANCELLED";
471
503
  } catch (ex) {
504
+ if (isUnencryptedContentRejectedError(ex)) {
505
+ this.replicationErrored(ex);
506
+ return "FAILED";
507
+ }
472
508
  Logger(`Unexpected synchronization exception`);
473
509
  Logger(ex, LOG_LEVEL_VERBOSE);
474
510
  return "FAILED";
@@ -1444,6 +1480,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1444
1480
  ...connectionOptions,
1445
1481
  encryptionAlgorithm: settings.E2EEAlgorithm,
1446
1482
  encryptInternalMetadata: usesEncryptedInternalMetadata(settings),
1483
+ acceptUnencryptedContent: settings.acceptUnencryptedContent === true,
1447
1484
  useCouchDBCacheControlHeadersOnly: settings.useCouchDBCacheControlHeadersOnly === true
1448
1485
  }
1449
1486
  );
@@ -1,5 +1,7 @@
1
1
  export { CAPABILITY_NOT_APPLICABLE, CAPABILITY_NOT_IMPLEMENTED, CENTRAL_REMOTE_REPLICATION_READINESS, NO_INTERACTION, PEER_REPLICATION_READINESS, PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS, REPLICATION_CANCELLED, REPLICATION_COMPLETED, REPLICATION_PROGRESS_PRESENTATIONS, USER_INITIATED_REPLICATION_AUTHORITY, defineReplicatorProviderDefinitions, isReplicationCompleted, outcomeFromContinuousOpenReplication, outcomeFromFiniteOpenReplication, replicationBlocked, replicationFailed, supportedOpenReplicationContinuous, supportedOpenReplicationOneShot, supportedOpenReplicationUnattended, supportedStopActiveTransfer, supportedCapability, } from "./ReplicatorProvider.js";
2
2
  export type { ReplicatorInstance } from "./ReplicatorInstance.js";
3
+ export { isUnencryptedContentRejectedError, UnencryptedContentRejectedError } from "./UnencryptedContentRejectedError.js";
4
+ export type { UnencryptedContentKind } from "./UnencryptedContentRejectedError.js";
3
5
  export type { ActiveReplicatorContext, CapabilitySupport, ContinuousReplicationRequest, ContinuousReplicationTrigger, ContinuousRunner, InteractionAuthority, InteractionPermissions, NotApplicableCapability, NotImplementedCapability, NoInteraction, PermittedInteractionPermissions, ReplicationBlockReason, ReplicationAttemptFailure, ReplicationCancelled, ReplicationCompleted, ReplicationFailed, ReplicationInteraction, ReplicationOutcome, ReplicationProgressPresentation, ReplicationReadinessRequirements, ReplicationPartial, ReplicationFailureRequest, ReplicatorConfigurationIdentity, ReplicatorProviderDefinition, ReplicatorProviderDefinitionMap, StopActiveTransferRunner, SupportedCapability, UnattendedOneShotRequest, UnattendedReplicationTrigger, UnattendedOneShotRunner, UserInitiatedOneShotRequest, UserInitiatedReplicationAuthority, UserInitiatedOneShotRunner, } from "./ReplicatorProvider.js";
4
6
  export { CAPABILITY_SUPPORT_KINDS, CAPABILITY_UNAVAILABLE_REASONS } from "./ProviderCapability.js";
5
7
  export { NO_REMOTE_RESOURCE_CAPABILITIES, REMOTE_RESOURCE_KINDS } from "./RemoteResource.js";
@@ -21,6 +21,7 @@ import {
21
21
  supportedStopActiveTransfer,
22
22
  supportedCapability
23
23
  } from "./ReplicatorProvider.js";
24
+ import { isUnencryptedContentRejectedError, UnencryptedContentRejectedError } from "./UnencryptedContentRejectedError.js";
24
25
  import { CAPABILITY_SUPPORT_KINDS, CAPABILITY_UNAVAILABLE_REASONS } from "./ProviderCapability.js";
25
26
  import { NO_REMOTE_RESOURCE_CAPABILITIES, REMOTE_RESOURCE_KINDS } from "./RemoteResource.js";
26
27
  import {
@@ -67,6 +68,7 @@ export {
67
68
  REPLICATION_COMPLETED,
68
69
  REPLICATION_PROGRESS_PRESENTATIONS,
69
70
  USER_INITIATED_REPLICATION_AUTHORITY,
71
+ UnencryptedContentRejectedError,
70
72
  applyCentralRemoteAdministrationMutation,
71
73
  assessRemoteFeatureDocument,
72
74
  centralRemoteAdministrationVerificationFailed,
@@ -76,6 +78,7 @@ export {
76
78
  inspectDatabasePathIdentity,
77
79
  isCentralRemoteAdministrationVerified,
78
80
  isReplicationCompleted,
81
+ isUnencryptedContentRejectedError,
79
82
  milestoneSatisfiesCentralRemoteAdministration,
80
83
  outcomeFromContinuousOpenReplication,
81
84
  outcomeFromFiniteOpenReplication,
@@ -249,6 +249,7 @@ export declare class TrysteroReplicator {
249
249
  forcePathStyle?: boolean;
250
250
  remoteType?: import("../../common/types.js").RemoteType;
251
251
  encrypt?: boolean;
252
+ acceptUnencryptedContent?: boolean;
252
253
  passphrase?: string;
253
254
  idDerivationKey?: string;
254
255
  usePathObfuscation?: boolean;
@@ -440,6 +441,7 @@ export declare class TrysteroReplicator {
440
441
  forcePathStyle?: boolean;
441
442
  remoteType?: import("../../common/types.js").RemoteType;
442
443
  encrypt?: boolean;
444
+ acceptUnencryptedContent?: boolean;
443
445
  passphrase?: string;
444
446
  idDerivationKey?: string;
445
447
  usePathObfuscation?: boolean;
@@ -0,0 +1,8 @@
1
+ declare const rejectionConsequences: {
2
+ readonly replication: "Synchronisation stopped";
3
+ readonly "on-demand": "File content could not be retrieved";
4
+ readonly "fast-fetch": "Fast Fetch stopped without completing";
5
+ };
6
+ /** Explain a refused operation and its recovery action without including document content. */
7
+ export declare function getUnencryptedContentRejectionMessage(operation: keyof typeof rejectionConsequences): string;
8
+ export {};
@@ -0,0 +1,12 @@
1
+ const rejectionConsequences = {
2
+ replication: "Synchronisation stopped",
3
+ "on-demand": "File content could not be retrieved",
4
+ "fast-fetch": "Fast Fetch stopped without completing"
5
+ };
6
+ function getUnencryptedContentRejectionMessage(operation) {
7
+ const nextAction = operation === "on-demand" ? ", then retry the file retrieval." : ".";
8
+ return `${rejectionConsequences[operation]} because unencrypted content was rejected. Review the remote data and 'Accept unencrypted content' in the E2EE Advanced settings${nextAction}`;
9
+ }
10
+ export {
11
+ getUnencryptedContentRejectionMessage
12
+ };
@@ -1,3 +1,4 @@
1
+ import { getUnencryptedContentRejectionMessage } from "../replication/unencryptedContentMessages.js";
1
2
  import { FlagFilesHumanReadable } from "../common/models/redflag.const.js";
2
3
  import { REMOTE_COUCHDB, REMOTE_MINIO, REMOTE_P2P } from "../common/models/setting.const.js";
3
4
  import { DEFAULT_SETTINGS } from "../common/models/setting.const.defaults.js";
@@ -18,6 +19,10 @@ import {
18
19
  } from "../pouchdb/StreamingFetch.js";
19
20
  import { getConfiguredFunctionsForEncryption } from "../pouchdb/encryption.js";
20
21
  import { AuthorizationHeaderGenerator, generateCredentialObject } from "../replication/httplib.js";
22
+ import {
23
+ getUnencryptedContentRejection,
24
+ isUnencryptedContentRejectedError
25
+ } from "../replication/UnencryptedContentRejectedError.js";
21
26
  import { isRemediationModeActive, parseHeaderValues } from "../common/utils.js";
22
27
  import { sizeToHumanReadable } from "octagonal-wheels/number";
23
28
  import { REMOTE_RESOURCE_KINDS } from "../replication/index.js";
@@ -541,13 +546,16 @@ Are you sure you wish to proceed?`;
541
546
  let fastForwardResource;
542
547
  let fastForward;
543
548
  try {
544
- const enc = getConfiguredFunctionsForEncryption(
549
+ const decrypt = settings.encrypt ? getConfiguredFunctionsForEncryption(
545
550
  settings.passphrase,
546
551
  false,
547
552
  false,
548
553
  () => securitySeed.read(),
549
- settings.E2EEAlgorithm
550
- );
554
+ settings.E2EEAlgorithm,
555
+ false,
556
+ void 0,
557
+ settings.acceptUnencryptedContent
558
+ ).outgoing : async (doc) => doc;
551
559
  if (startsFresh && !settings.doNotSuspendOnFetching && (await localDB.info()).doc_count === 0) {
552
560
  fastForwardResource = await this.replicator.createRemoteResource(
553
561
  REMOTE_RESOURCE_KINDS.INITIAL_FETCH_FAST_FORWARD,
@@ -561,7 +569,7 @@ Are you sure you wish to proceed?`;
561
569
  localDB,
562
570
  remote,
563
571
  authHeader,
564
- enc.outgoing,
572
+ decrypt,
565
573
  since,
566
574
  (progress) => {
567
575
  this._log(
@@ -580,6 +588,22 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`,
580
588
  );
581
589
  break;
582
590
  } catch (ex) {
591
+ if (isUnencryptedContentRejectedError(ex)) {
592
+ this._log(
593
+ getUnencryptedContentRejectionMessage("fast-fetch"),
594
+ LOG_LEVEL_NOTICE,
595
+ "fetch-init-plaintext-rejected"
596
+ );
597
+ const rejection = getUnencryptedContentRejection(ex);
598
+ if (rejection) {
599
+ this._log(
600
+ `Fast Fetch rejected ${rejection.contentKind}: ${JSON.stringify(rejection.documentId)}`,
601
+ LOG_LEVEL_VERBOSE,
602
+ "fetch-init-plaintext-rejected"
603
+ );
604
+ }
605
+ throw ex;
606
+ }
583
607
  if (!isRetryableStreamingFetchFailure(ex) || attempt >= FAST_FETCH_RETRY_DELAYS.length) throw ex;
584
608
  checkpoint = await this.getFastFetchCheckpoint(remote);
585
609
  since = checkpoint?.sequence ?? since;