@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
@@ -0,0 +1,146 @@
1
+ import { getStoragePathComparisonKey } from "./pathComparison.js";
2
+ function validatePath(path) {
3
+ if (typeof path !== "string") {
4
+ throw new TypeError("File paths must be strings");
5
+ }
6
+ return path;
7
+ }
8
+ function snapshotPolicy(policy) {
9
+ const { pathNormalizationVersion, handleFilenameCaseSensitive } = policy;
10
+ if (pathNormalizationVersion !== 0 && pathNormalizationVersion !== 1) {
11
+ throw new Error(`Unsupported path normalisation version: ${pathNormalizationVersion}`);
12
+ }
13
+ if (typeof handleFilenameCaseSensitive !== "boolean") {
14
+ throw new TypeError("Filename case handling must be explicit");
15
+ }
16
+ return { pathNormalizationVersion, handleFilenameCaseSensitive };
17
+ }
18
+ function getPolicyKey(policy) {
19
+ return `${policy.pathNormalizationVersion}:${policy.handleFilenameCaseSensitive ? "sensitive" : "insensitive"}`;
20
+ }
21
+ function createIdentityBuckets(paths, policy) {
22
+ const buckets = /* @__PURE__ */ new Map();
23
+ for (const path of paths) {
24
+ const key = getStoragePathComparisonKey(path, policy);
25
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
26
+ bucket.add(path);
27
+ buckets.set(key, bucket);
28
+ }
29
+ return buckets;
30
+ }
31
+ class FilePathIndex {
32
+ paths = /* @__PURE__ */ new Set();
33
+ indexes = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Replace the complete inventory and all materialised policy maps together.
36
+ *
37
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
38
+ * into one membership without normalising their spelling.
39
+ * @throws Propagates invalid runtime members or iterable failures before
40
+ * replacing the current inventory or any existing policy map.
41
+ * @remarks
42
+ * Validation checks string members; filesystem admission remains the host's
43
+ * responsibility. Callers use this after a successful initial or fresh read.
44
+ */
45
+ replaceAll(paths) {
46
+ const nextPaths = /* @__PURE__ */ new Set();
47
+ for (const path of paths) {
48
+ nextPaths.add(validatePath(path));
49
+ }
50
+ const nextIndexes = /* @__PURE__ */ new Map();
51
+ for (const [key, { policy }] of this.indexes) {
52
+ nextIndexes.set(key, { policy, buckets: createIdentityBuckets(nextPaths, policy) });
53
+ }
54
+ this.paths = nextPaths;
55
+ this.indexes = nextIndexes;
56
+ }
57
+ /**
58
+ * Apply one membership delta to the inventory and every cached policy map.
59
+ *
60
+ * @param delta - Original paths removed and added by the same change.
61
+ * @throws Propagates invalid runtime members before changing retained state.
62
+ * @remarks
63
+ * Inputs and comparison keys are prepared before mutation. The synchronous
64
+ * update publishes no intermediate rename state. Repeated notifications do
65
+ * not create duplicate memberships, and content-only edits need no delta.
66
+ */
67
+ apply(delta) {
68
+ const removed = new Set(delta.removed.map(validatePath));
69
+ const added = new Set(delta.added.map(validatePath));
70
+ for (const path of added) {
71
+ if (removed.has(path)) {
72
+ removed.delete(path);
73
+ if (this.paths.has(path)) {
74
+ added.delete(path);
75
+ }
76
+ }
77
+ }
78
+ const actualRemoved = [...removed].filter((path) => this.paths.has(path));
79
+ const actualAdded = [...added].filter((path) => !this.paths.has(path));
80
+ if (actualRemoved.length === 0 && actualAdded.length === 0) {
81
+ return;
82
+ }
83
+ const indexUpdates = [...this.indexes.values()].map(({ buckets, policy }) => ({
84
+ buckets,
85
+ removed: actualRemoved.map((path) => [getStoragePathComparisonKey(path, policy), path]),
86
+ added: actualAdded.map((path) => [getStoragePathComparisonKey(path, policy), path])
87
+ }));
88
+ for (const path of actualRemoved) {
89
+ this.paths.delete(path);
90
+ }
91
+ for (const path of actualAdded) {
92
+ this.paths.add(path);
93
+ }
94
+ for (const { buckets, removed: removedKeys, added: addedKeys } of indexUpdates) {
95
+ for (const [key, path] of removedKeys) {
96
+ const bucket = buckets.get(key);
97
+ bucket?.delete(path);
98
+ if (bucket?.size === 0) {
99
+ buckets.delete(key);
100
+ }
101
+ }
102
+ for (const [key, path] of addedKeys) {
103
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
104
+ bucket.add(path);
105
+ buckets.set(key, bucket);
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Copy the current in-memory membership without refreshing the host listing.
111
+ *
112
+ * @returns Original spellings in an independent array. Full-list ordering is
113
+ * unspecified; changing the returned array cannot change this index.
114
+ */
115
+ getFileNames() {
116
+ return [...this.paths];
117
+ }
118
+ /**
119
+ * Select every indexed path with the requested storage comparison key.
120
+ *
121
+ * @param path - Path whose identity selects a candidate bucket.
122
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
123
+ * @returns A sorted copy of all matching original paths, or an empty array
124
+ * when no indexed path matches. Multiple paths remain separate candidates.
125
+ * @throws Rejects a non-string path or unsupported comparison settings.
126
+ * @remarks
127
+ * The first query for each policy materialises its buckets. Later membership
128
+ * deltas maintain those buckets incrementally. Host readiness, existence,
129
+ * physical alias checks, and the final collision decision are external.
130
+ */
131
+ findPathIdentityCandidates(path, policy) {
132
+ const validatedPath = validatePath(path);
133
+ const policySnapshot = snapshotPolicy(policy);
134
+ const policyKey = getPolicyKey(policySnapshot);
135
+ let index = this.indexes.get(policyKey);
136
+ if (!index) {
137
+ index = { policy: policySnapshot, buckets: createIdentityBuckets(this.paths, policySnapshot) };
138
+ this.indexes.set(policyKey, index);
139
+ }
140
+ const key = getStoragePathComparisonKey(validatedPath, policySnapshot);
141
+ return [...index.buckets.get(key) ?? []].sort();
142
+ }
143
+ }
144
+ export {
145
+ FilePathIndex
146
+ };
@@ -1,5 +1,4 @@
1
1
  import type { EntryDoc } from "../common/models/db.definition.js";
2
- import type { AnyEntry, EntryLeaf } from "../common/models/db.type.js";
3
2
  type DBSequence = number | string;
4
3
  /**
5
4
  * Identifies the boundary at which Fast Fetch stopped.
@@ -56,7 +55,7 @@ export type FetchChangesForInitialSyncProgress = {
56
55
  * @param customHeaders Additional request headers required by the CouchDB endpoint or its reverse proxy.
57
56
  * @param onStoredRevisions Observes revision identities after their complete local batch is persisted.
58
57
  */
59
- export declare function fetchChangesForInitialSync(downloadToDB: PouchDB.Database, remoteDbUrl: string, authHeader: string, decryptFunction: (doc: EntryDoc) => Promise<AnyEntry | EntryLeaf>, since?: number | string, onProgress?: (progress: FetchChangesForInitialSyncProgress) => void, onCheckpoint?: (sequence: DBSequence) => void | Promise<void>, customHeaders?: Record<string, string>, onStoredRevisions?: (revisions: readonly {
58
+ export declare function fetchChangesForInitialSync(downloadToDB: PouchDB.Database, remoteDbUrl: string, authHeader: string, decryptFunction: (doc: EntryDoc) => Promise<EntryDoc>, since?: number | string, onProgress?: (progress: FetchChangesForInitialSyncProgress) => void, onCheckpoint?: (sequence: DBSequence) => void | Promise<void>, customHeaders?: Record<string, string>, onStoredRevisions?: (revisions: readonly {
60
59
  id: string;
61
60
  rev: string;
62
61
  }[]) => void | Promise<void>): Promise<void>;
@@ -1,6 +1,7 @@
1
- import { Logger } from "../common/logger.js";
2
- import { type EntryDoc, type AnyEntry, type EntryLeaf, type DocumentID, type E2EEAlgorithm } from "../common/types.js";
1
+ import { type EntryDoc, type AnyEntry, type EntryLeaf, type E2EEAlgorithm } from "../common/types.js";
3
2
  import { encryptWorker, decryptWorker, encryptHKDFWorker, decryptHKDFWorker } from "#worker";
3
+ import type { LogFunction } from "../services/lib/logUtils.js";
4
+ export { EDEN_ENCRYPTED_KEY, EDEN_ENCRYPTED_KEY_HKDF, shouldEncryptEden, shouldEncryptEdenHKDF, shouldDecryptEden, shouldDecryptEdenHKDF, } from "./encryption.eden.js";
4
5
  export declare const encrypt: typeof encryptWorker;
5
6
  export declare const decrypt: typeof decryptWorker;
6
7
  export declare const encryptHKDF: typeof encryptHKDFWorker;
@@ -8,15 +9,9 @@ export declare const decryptHKDF: typeof decryptHKDFWorker;
8
9
  export declare function isEncryptedMeta<T extends AnyEntry>(doc: T): boolean;
9
10
  export declare let preprocessOutgoing: (doc: AnyEntry | EntryLeaf) => Promise<AnyEntry | EntryLeaf>;
10
11
  export declare let preprocessIncoming: (doc: EntryDoc) => Promise<EntryDoc>;
11
- export declare function getConfiguredFunctionsForEncryption(passphrase: string, useDynamicIterationCount: boolean, migrationDecrypt: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, algorithm: E2EEAlgorithm, encryptInternalMetadata?: boolean, log?: typeof Logger): {
12
+ export declare function getConfiguredFunctionsForEncryption(passphrase: string, useDynamicIterationCount: boolean, migrationDecrypt: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, algorithm: E2EEAlgorithm, encryptInternalMetadata?: boolean, log?: LogFunction, acceptUnencryptedContent?: boolean): {
12
13
  incoming: (doc: AnyEntry | EntryLeaf) => Promise<AnyEntry | EntryLeaf>;
13
14
  outgoing: (doc: EntryDoc) => Promise<AnyEntry | EntryLeaf>;
14
15
  };
15
- export declare const enableEncryption: (db: PouchDB.Database<EntryDoc>, passphrase: string, useDynamicIterationCount: boolean, migrationDecrypt: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, algorithm: E2EEAlgorithm, encryptInternalMetadata?: boolean) => void;
16
+ export declare const enableEncryption: (db: PouchDB.Database<EntryDoc>, passphrase: string, useDynamicIterationCount: boolean, migrationDecrypt: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, algorithm: E2EEAlgorithm, encryptInternalMetadata?: boolean, acceptUnencryptedContent?: boolean) => void;
16
17
  export declare function disableEncryption(): void;
17
- export declare const EDEN_ENCRYPTED_KEY: DocumentID;
18
- export declare const EDEN_ENCRYPTED_KEY_HKDF: DocumentID;
19
- export declare function shouldEncryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
20
- export declare function shouldEncryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
21
- export declare function shouldDecryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
22
- export declare function shouldDecryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Eden is being phased out. Avoid proactive refactoring or enhancements;
3
+ * limit changes to necessary fixes and compatibility maintenance.
4
+ */
5
+ import type { AnyEntry, EntryLeaf, DocumentID } from "../common/types.js";
6
+ export declare const EDEN_ENCRYPTED_KEY: DocumentID;
7
+ export declare const EDEN_ENCRYPTED_KEY_HKDF: DocumentID;
8
+ export declare function shouldEncryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
9
+ export declare function shouldEncryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
10
+ export declare function shouldDecryptEden(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
11
+ export declare function shouldDecryptEdenHKDF(doc: AnyEntry | EntryLeaf): doc is AnyEntry;
@@ -0,0 +1,37 @@
1
+ const EDEN_ENCRYPTED_KEY = "h:++encrypted";
2
+ const EDEN_ENCRYPTED_KEY_HKDF = "h:++encrypted-hkdf";
3
+ function shouldEncryptEden(doc) {
4
+ if ("eden" in doc && !(EDEN_ENCRYPTED_KEY in doc.eden)) {
5
+ return true;
6
+ }
7
+ return false;
8
+ }
9
+ function shouldEncryptEdenHKDF(doc) {
10
+ if ("eden" in doc && !(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)) {
11
+ if (Object.keys(doc.eden).length === 0) {
12
+ return false;
13
+ }
14
+ return true;
15
+ }
16
+ return false;
17
+ }
18
+ function shouldDecryptEden(doc) {
19
+ if ("eden" in doc && EDEN_ENCRYPTED_KEY in doc.eden) {
20
+ return true;
21
+ }
22
+ return false;
23
+ }
24
+ function shouldDecryptEdenHKDF(doc) {
25
+ if ("eden" in doc && EDEN_ENCRYPTED_KEY_HKDF in doc.eden) {
26
+ return true;
27
+ }
28
+ return false;
29
+ }
30
+ export {
31
+ EDEN_ENCRYPTED_KEY,
32
+ EDEN_ENCRYPTED_KEY_HKDF,
33
+ shouldDecryptEden,
34
+ shouldDecryptEdenHKDF,
35
+ shouldEncryptEden,
36
+ shouldEncryptEdenHKDF
37
+ };
@@ -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
+ };