@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
@@ -1,80 +1,176 @@
1
+ import { createReplicationProgress } from "./TrysteroReplicator/progress.js";
2
+ import { createTransfers, p2pReplicationFailed } from "./TrysteroReplicator/transfers.js";
3
+ import { createConfiguredTargets } from "./TrysteroReplicator/configuredTargets.js";
4
+ import { createConfigurationExchange } from "./TrysteroReplicator/configurationExchange.js";
5
+ import { createPeerAgreement } from "./TrysteroReplicator/peerAgreement.js";
6
+ import { createChangeRelay } from "./TrysteroReplicator/changeRelay.js";
1
7
  import { reportP2PDiagnostic } from "../../p2p/p2pDiagnostics.js";
2
- import {
3
- authenticationResultDiagnostic,
4
- authenticationFailureDiagnostic,
5
- pullResultDiagnostic,
6
- pullFailureDiagnostic,
7
- notificationFailureDiagnostic
8
- } from "./p2pReplicationDiagnostics.js";
9
- import {
10
- projectDirectionProgress,
11
- projectAcknowledgedAttempt
12
- } from "./p2pReplicationProgress.js";
13
8
  import { parsePeerPatterns } from "./peerPatterns.js";
14
- import {
15
- TweakValuesShouldMatchedTemplate,
16
- omitP2PRuntimeSettings
17
- } from "../../common/types.js";
18
- import { assessTweakCompatibility } from "../../common/models/tweak.compatibility.js";
19
- import {
20
- LOG_LEVEL_INFO,
21
- LOG_LEVEL_NOTICE,
22
- LOG_LEVEL_VERBOSE,
23
- Logger
24
- } from "octagonal-wheels/common/logger";
9
+ import {} from "../../common/types.js";
10
+ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, Logger } from "octagonal-wheels/common/logger";
25
11
  import { replicateShim } from "../../pouchdb/ReplicatorShim.js";
26
12
  import { resolveCurrentP2PSettings } from "./types.js";
27
- import { scheduleOnceIfDuplicated, serialized, skipIfDuplicated } from "octagonal-wheels/concurrency/lock_v2";
28
- import { delay, fireAndForget } from "octagonal-wheels/promises";
13
+ import { skipIfDuplicated } from "octagonal-wheels/concurrency/lock_v2";
29
14
  import {
30
15
  EVENT_ADVERTISEMENT_RECEIVED,
31
16
  EVENT_P2P_REPLICATOR_PROGRESS,
32
17
  EVENT_P2P_REPLICATOR_STATUS,
33
18
  P2PHost
34
19
  } from "./TrysteroReplicatorP2PServer.js";
35
- import { encryptWithEphemeralSalt, decryptWithEphemeralSalt } from "octagonal-wheels/encryption/hkdf";
36
- import { sha1 } from "octagonal-wheels/hash/purejs";
37
- import { getRelaySockets, pauseRelayReconnection, resumeRelayReconnection } from "@trystero-p2p/nostr";
20
+ import { defaultRelayControl, disconnectRelay } from "./TrysteroReplicator/relayControl.js";
38
21
  import { P2PAutomationCoordinator } from "./P2PAutomationCoordinator.js";
39
22
  import { compatGlobal } from "../../common/coreEnvFunctions.js";
40
- import { computeKeyedId, configuredIdKey } from "../../common/idDerivation.js";
41
- import { getWebCrypto } from "../../mods.js";
42
- import { uint8ArrayToHexString } from "../../string_and_binary/convert.js";
43
- import { getPathNormalizationVersion } from "../../common/pathNormalization.js";
44
- import { readLocalP2PPathIdentity, readRemoteP2PPathIdentity } from "./TrysteroReplicator.pathIdentity.js";
45
23
  import { assertDatabasePathIdentity } from "../../pouchdb/pathIdentityCompatibility.js";
46
- import {
47
- fromP2PReplicationWireResult,
48
- toP2PReplicationWireResult,
49
- toP2PWireError
50
- } from "./P2PReplicationWire.js";
51
- async function encrypt(data, passphrase) {
52
- return await encryptWithEphemeralSalt(data, passphrase, true);
53
- }
54
- async function decrypt(encryptedData, passphrase) {
55
- return await decryptWithEphemeralSalt(encryptedData, passphrase);
56
- }
57
- let nextProgressAttempt = 0;
58
- const P2P_REPLICATION_COMPLETED = Object.freeze({ status: "completed", ok: true });
59
- const P2P_REPLICATION_CANCELLED = Object.freeze({ status: "cancelled" });
60
- function p2pReplicationFailed(error) {
61
- return { status: "failed", error };
62
- }
63
- function isP2PReplicationCancelled(result) {
64
- return result.status === "cancelled";
65
- }
66
- async function getHashedStringWithCurrentTime(source) {
67
- const salt = (~~((/* @__PURE__ */ new Date()).getTime() / 1e3 / 180)).toString(36);
68
- const salt2 = await sha1(salt);
69
- return await sha1(salt2 + source);
70
- }
24
+ import { toP2PReplicationWireResult, toP2PWireError } from "./P2PReplicationWire.js";
71
25
  class TrysteroReplicator {
72
26
  _env;
73
27
  finiteOperationOwner;
28
+ relayControl;
74
29
  disposed = false;
75
- acknowledgedAttempts = /* @__PURE__ */ new Map();
76
30
  fallbackAutomationCoordinator = new P2PAutomationCoordinator();
77
31
  server;
32
+ replicationProgress = createReplicationProgress({
33
+ isDisposed: () => this.disposed,
34
+ peerName: (peerId) => this.server?._knownAdvertisements?.get(peerId)?.name,
35
+ emitProgress: (report) => this._env.events.emitEvent(EVENT_P2P_REPLICATOR_PROGRESS, report),
36
+ captureAcknowledgementTarget: (peerId) => {
37
+ const server = this.server;
38
+ if (!server) {
39
+ return void 0;
40
+ }
41
+ return {
42
+ send: (info, acknowledgement) => server.getConnection(peerId).invokeRemoteFunction(
43
+ "onProgressAcknowledged",
44
+ [server.serverPeerId, info, acknowledgement],
45
+ 500
46
+ )
47
+ };
48
+ }
49
+ });
50
+ transfers = createTransfers({
51
+ host: () => {
52
+ const server = this.server;
53
+ if (!server) {
54
+ return void 0;
55
+ }
56
+ return {
57
+ connection: (peerId) => {
58
+ const connection = server.getConnection(peerId);
59
+ return {
60
+ requestSynchronisation: (timeoutMs, signal) => connection.invokeRemoteFunction(
61
+ "reqSync",
62
+ [server.serverPeerId],
63
+ timeoutMs,
64
+ signal
65
+ ),
66
+ getRemoteDB: (signal) => connection.getRemoteDB(signal)
67
+ };
68
+ }
69
+ };
70
+ },
71
+ database: () => this.db,
72
+ currentSettings: () => this.currentSettings,
73
+ replicate: replicateShim,
74
+ processReplicatedDocs: (docs) => this._env.processReplicatedDocs(docs),
75
+ canStartOrdinaryReplication: (...args) => this.canStartOrdinaryReplication(...args),
76
+ requestAuthenticate: (...args) => this.requestAuthenticate(...args),
77
+ checkTweakValues: (...args) => this.checkTweakValues(...args),
78
+ replicateFrom: (...args) => this.replicateFrom(...args),
79
+ requestSynchroniseToPeer: (...args) => this.requestSynchroniseToPeer(...args),
80
+ dispatchStatus: () => this.dispatchStatus(),
81
+ dispatchReplicationProgress: (...args) => this.dispatchReplicationProgress(...args),
82
+ acknowledgeProgress: (...args) => this.acknowledgeProgress(...args),
83
+ beginProgressAttempt: () => this.replicationProgress.beginAttempt(),
84
+ reportDiagnostic: (input) => this.reportDiagnostic(input),
85
+ notifyProgress: (...args) => this.notifyProgress(...args)
86
+ });
87
+ configuredTargets = createConfiguredTargets({
88
+ currentSettings: () => this.currentSettings,
89
+ advertisements: () => this.knownAdvertisements,
90
+ evaluatePeerAcceptance: (peerId) => this.server?.evaluatePeerAcceptance(peerId) ?? Promise.resolve(void 0),
91
+ runBaseline: (...args) => this.automationCoordinator.runBaseline(...args),
92
+ sync: (...args) => this.sync(...args),
93
+ onAdvertisement: (listener) => this._env.events.onEvent(EVENT_ADVERTISEMENT_RECEIVED, listener),
94
+ scheduleTimeout: (callback, delayMs) => {
95
+ const handle = compatGlobal.setTimeout(callback, delayMs);
96
+ return () => compatGlobal.clearTimeout(handle);
97
+ },
98
+ translate: (...args) => this.translate(...args)
99
+ });
100
+ // Assembly keeps room identity in the host while agreement operations receive
101
+ // only the connection, settings, and validation capabilities they use.
102
+ peerAgreement = createPeerAgreement({
103
+ host: () => {
104
+ const server = this.server;
105
+ if (!server) {
106
+ return void 0;
107
+ }
108
+ return {
109
+ peerPlatform: (peerId) => server.knownAdvertisements.find((peer) => peer.peerId == peerId)?.platform,
110
+ connection: (peerId) => {
111
+ const connection = server.getConnection(peerId);
112
+ return {
113
+ requestAuthentication: (timeoutMs, signal) => connection.invokeRemoteObjectFunction(
114
+ "!reqAuth",
115
+ [server.serverPeerId],
116
+ timeoutMs,
117
+ signal
118
+ ),
119
+ requestTweakSettings: (challenge, timeoutMs, signal) => connection.invokeRemoteObjectFunction("getTweakSettings", [challenge], timeoutMs, signal)
120
+ };
121
+ }
122
+ };
123
+ },
124
+ settings: () => this.settings,
125
+ currentSettings: () => this.currentSettings,
126
+ platform: () => this.platform,
127
+ assertPathIdentity: async (settings) => {
128
+ await assertDatabasePathIdentity(this.db, settings, true);
129
+ },
130
+ localTweakSettings: (challenge) => this.getTweakSettings(challenge),
131
+ reportDiagnostic: (input) => this.reportDiagnostic(input)
132
+ });
133
+ configurationExchange = createConfigurationExchange({
134
+ isSetup: () => this._onSetup,
135
+ settings: () => this.settings,
136
+ // Resolve the current host services at use time and retain Confirm's receiver.
137
+ askString: (...args) => this.confirm.askString(...args),
138
+ translate: (key) => this.translate(key),
139
+ host: () => {
140
+ const server = this.server;
141
+ if (!server) {
142
+ return void 0;
143
+ }
144
+ return {
145
+ requestConfiguration: (peerId, timeoutMs) => {
146
+ const connection = server.getConnection(peerId);
147
+ return connection.invokeRemoteFunction("getAllConfig", [server.serverPeerId], timeoutMs);
148
+ }
149
+ };
150
+ }
151
+ });
152
+ changeRelay = createChangeRelay({
153
+ createChangesFeed: (options) => this.db.changes(options),
154
+ hasHost: () => Boolean(this.server),
155
+ peerIds: () => this.server?.knownAdvertisements.map(({ peerId }) => peerId) ?? [],
156
+ captureNotificationTarget: (peerId) => {
157
+ const server = this.server;
158
+ const room = server?.rpcRoom;
159
+ if (!server || !room) {
160
+ return void 0;
161
+ }
162
+ return {
163
+ isAccepted: () => server.isAcceptablePeer(peerId),
164
+ isCurrent: () => this.server === server && server.rpcRoom === room,
165
+ send: () => server.getConnection(peerId).notifyRemoteFunction("onProgress", [server.serverPeerId])
166
+ };
167
+ },
168
+ isDisposed: () => this.disposed,
169
+ announceChanges: () => this.notifyProgress(),
170
+ pullPeer: (peerId) => this.runFiniteReplicationActivity(() => this.replicateFrom(peerId)),
171
+ dispatchStatus: () => this.dispatchStatus(),
172
+ reportDiagnostic: (input) => this.reportDiagnostic(input)
173
+ });
78
174
  replicationStatus() {
79
175
  return {};
80
176
  }
@@ -83,6 +179,7 @@ class TrysteroReplicator {
83
179
  reportP2PDiagnostic(this._env.reportDiagnostic, input);
84
180
  }
85
181
  }
182
+ /** Immutable room settings used for transport binding and shared configuration. */
86
183
  get settings() {
87
184
  return this._env.settings;
88
185
  }
@@ -117,9 +214,10 @@ class TrysteroReplicator {
117
214
  async canStartOrdinaryReplication(showMessage = false) {
118
215
  return this._env.canStartOrdinaryReplication ? await this._env.canStartOrdinaryReplication(showMessage) : true;
119
216
  }
120
- constructor(env, server, finiteOperationOwner) {
217
+ constructor(env, server, finiteOperationOwner, options = {}) {
121
218
  this._env = env;
122
219
  this.finiteOperationOwner = finiteOperationOwner;
220
+ this.relayControl = options.relayControl ?? defaultRelayControl;
123
221
  if (server) {
124
222
  this.server = server;
125
223
  return;
@@ -147,6 +245,7 @@ class TrysteroReplicator {
147
245
  throw e;
148
246
  }
149
247
  }
248
+ /** Borrow the session owner's cancellation scope; legacy direct hosts use the caller signal. */
150
249
  async runSessionFiniteOperation(task, callerSignal) {
151
250
  if (this.finiteOperationOwner) {
152
251
  return await this.finiteOperationOwner.runFiniteOperation(task, callerSignal);
@@ -156,9 +255,8 @@ class TrysteroReplicator {
156
255
  async close() {
157
256
  this.requestStatus();
158
257
  await this.server?.shutdown();
159
- this.acknowledgedAttempts.clear();
160
- this._replicateFromPeers.clear();
161
- this._replicateToPeers.clear();
258
+ this.replicationProgress.clear();
259
+ this.transfers.clearActivePeers();
162
260
  this._watchingPeers.clear();
163
261
  this.requestStatus();
164
262
  this.disconnectFromServer();
@@ -243,7 +341,7 @@ class TrysteroReplicator {
243
341
  });
244
342
  }
245
343
  onPeerLeaved(peerId) {
246
- this.acknowledgedAttempts.delete(peerId);
344
+ this.replicationProgress.peerLeft(peerId);
247
345
  void this.unwatchPeer(peerId);
248
346
  }
249
347
  _onSetup = false;
@@ -253,34 +351,9 @@ class TrysteroReplicator {
253
351
  clearOnSetup() {
254
352
  this._onSetup = false;
255
353
  }
354
+ /** Build challenge-bound compatibility data without exposing local ID keys. */
256
355
  async getTweakSettings(fromPeerId) {
257
- const currentSettings = this.currentSettings;
258
- const pathNormalizationVersion = getPathNormalizationVersion(currentSettings);
259
- if (pathNormalizationVersion === 1) {
260
- await assertDatabasePathIdentity(this.db, currentSettings, true);
261
- }
262
- const allSettings = JSON.parse(JSON.stringify(this.settings));
263
- for (const key in allSettings) {
264
- if (key == "encrypt") {
265
- continue;
266
- }
267
- if (key == "passphrase") {
268
- allSettings[key] = await getHashedStringWithCurrentTime(allSettings[key] ?? "");
269
- continue;
270
- }
271
- if (!(key in TweakValuesShouldMatchedTemplate)) {
272
- delete allSettings[key];
273
- }
274
- }
275
- const idSettings = this.currentSettings;
276
- const idDerivationVersion = idSettings.idDerivationVersion ?? 0;
277
- const idKey = configuredIdKey({ idDerivationVersion, idDerivationKey: idSettings.idDerivationKey ?? "" });
278
- return {
279
- ...allSettings,
280
- pathNormalizationVersion,
281
- idDerivationVersion,
282
- idDerivationProof: idKey && idSettings.encrypt && idSettings.usePathObfuscation ? await computeKeyedId(idKey, "peer-agreement", fromPeerId) : ""
283
- };
356
+ return await this.peerAgreement.getTweakSettings(fromPeerId);
284
357
  }
285
358
  async handleSynchronisationRequest(fromPeerId, signal) {
286
359
  if (this._onSetup) {
@@ -290,17 +363,25 @@ class TrysteroReplicator {
290
363
  () => signal ? this.replicateFrom(fromPeerId, false, false, false, signal) : this.replicateFrom(fromPeerId)
291
364
  );
292
365
  }
366
+ /**
367
+ * Build the existing wire command object against this facade.
368
+ * Public method dispatch stays dynamic for host overrides; RpcRoom owns
369
+ * serialisation, request context, and call-versus-notification responses.
370
+ */
293
371
  getCommands() {
294
372
  return {
295
373
  // The wire-visible command deliberately accepts only serialisable
296
374
  // arguments. RpcRoom supplies cancellation context separately.
297
375
  reqSync: async (fromPeerId) => toP2PReplicationWireResult(await this.handleSynchronisationRequest(fromPeerId)),
376
+ // Incoming admission remains with the host's peer-acceptance policy.
298
377
  "!reqAuth": async (fromPeerId) => {
299
378
  return await this.server?.isAcceptablePeer(fromPeerId);
300
379
  },
301
380
  getTweakSettings: async (fromPeerId) => {
302
381
  return await this.getTweakSettings(fromPeerId);
303
382
  },
383
+ // Remote acquisition runs through the relay; notification send completion
384
+ // at the caller does not wait for this handler's pull result.
304
385
  onProgress: async (fromPeerId) => {
305
386
  if (this._onSetup) {
306
387
  this.reportDiagnostic({
@@ -314,43 +395,7 @@ class TrysteroReplicator {
314
395
  await this.onUpdateDatabase(fromPeerId);
315
396
  },
316
397
  getAllConfig: async (fromPeerId) => {
317
- if (this._onSetup) {
318
- return { error: toP2PWireError(new Error("The setup is in progress")) };
319
- }
320
- const passphrase = await skipIfDuplicated(`getAllConfig-${fromPeerId}`, async () => {
321
- return await this.confirm.askString(
322
- "Passphrase required",
323
- this.translate("P2P.AskPassphraseForShare"),
324
- "something you only know",
325
- true
326
- );
327
- });
328
- const setting = {
329
- ...omitP2PRuntimeSettings(this.settings),
330
- configPassphraseStore: "",
331
- encryptedCouchDBConnection: "",
332
- encryptedPassphrase: "",
333
- pluginSyncExtendedSetting: {}
334
- };
335
- delete setting.P2P_managedType;
336
- delete setting.P2P_managedId;
337
- delete setting.P2P_managedToken;
338
- if (!passphrase || passphrase.trim() == "") {
339
- Logger(
340
- "Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.",
341
- LOG_LEVEL_NOTICE
342
- );
343
- const r = JSON.stringify(
344
- Object.fromEntries(
345
- Object.entries(setting).map(([key, value]) => {
346
- return [key, "******".repeat(Math.ceil(Math.random() * 10) + 2)];
347
- })
348
- )
349
- );
350
- const randomString = Math.random().toString(36).substring(7);
351
- return encrypt(r, randomString);
352
- }
353
- return encrypt(JSON.stringify(setting), passphrase.trim());
398
+ return await this.configurationExchange.shareConfiguration(fromPeerId);
354
399
  },
355
400
  onProgressAcknowledged: async (fromPeerId, info, acknowledgement) => {
356
401
  try {
@@ -382,63 +427,24 @@ class TrysteroReplicator {
382
427
  }
383
428
  };
384
429
  }
430
+ /** Retain the public admission entry point and its caller cancellation signal. */
385
431
  async requestAuthenticate(peerId, signal) {
386
- if (!this.server) return false;
387
- try {
388
- const connection = this.server.getConnection(peerId);
389
- const selfPeerId = this.server.serverPeerId;
390
- const r = await connection.invokeRemoteObjectFunction(
391
- "!reqAuth",
392
- [selfPeerId],
393
- 2e4,
394
- signal
395
- );
396
- this.reportDiagnostic(authenticationResultDiagnostic(peerId, r));
397
- return r;
398
- } catch (e) {
399
- this.reportDiagnostic(authenticationFailureDiagnostic(peerId, e, signal));
400
- Logger("Error while requesting authentication", LOG_LEVEL_VERBOSE);
401
- Logger(e, LOG_LEVEL_VERBOSE);
402
- return false;
403
- }
432
+ return await this.peerAgreement.requestAuthenticate(peerId, signal);
433
+ }
434
+ get lastSeq() {
435
+ return this.changeRelay.lastSeq;
436
+ }
437
+ set lastSeq(sequence) {
438
+ this.changeRelay.lastSeq = sequence;
404
439
  }
405
- lastSeq = "";
406
440
  async requestSynchroniseToPeer(peerId, callerSignal) {
407
441
  return await this.runSessionFiniteOperation(
408
- async (signal) => await this.requestSynchroniseToPeerWithinSession(peerId, signal),
442
+ async (signal) => await this.transfers.requestSynchroniseToPeer(peerId, signal),
409
443
  callerSignal
410
444
  );
411
445
  }
412
- async requestSynchroniseToPeerWithinSession(peerId, signal) {
413
- if (!await this.canStartOrdinaryReplication(false)) {
414
- return p2pReplicationFailed(new Error("Replication is not ready"));
415
- }
416
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
417
- await delay(25);
418
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
419
- if (!this.server) throw new Error("Server is not available");
420
- const conn = this.server.getConnection(peerId);
421
- try {
422
- const result = await conn.invokeRemoteFunction(
423
- "reqSync",
424
- [this.server.serverPeerId],
425
- 0,
426
- signal
427
- );
428
- return fromP2PReplicationWireResult(result);
429
- } catch (error) {
430
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
431
- throw error;
432
- }
433
- }
434
446
  async requestSynchroniseToAllAvailablePeers() {
435
- await scheduleOnceIfDuplicated("requestSynchroniseToAllAvailablePeers", async () => {
436
- await delay(25);
437
- const replications = [...this.availableReplicationPairs].map((peerId) => {
438
- return this.requestSynchroniseToPeer(peerId);
439
- });
440
- await Promise.all(replications);
441
- });
447
+ return await this.transfers.requestSynchroniseToAllAvailablePeers();
442
448
  }
443
449
  dispatchStatus() {
444
450
  if (this.disposed) return;
@@ -453,65 +459,23 @@ class TrysteroReplicator {
453
459
  this.dispatchStatus();
454
460
  void this.server?.dispatchConnectionStatus();
455
461
  }
456
- changes;
457
- _isBroadcasting = false;
462
+ get changes() {
463
+ return this.changeRelay.changes;
464
+ }
465
+ set changes(changes) {
466
+ this.changeRelay.changes = changes;
467
+ }
468
+ get _isBroadcasting() {
469
+ return this.changeRelay.isBroadcasting;
470
+ }
471
+ set _isBroadcasting(enabled) {
472
+ this.changeRelay.isBroadcasting = enabled;
473
+ }
458
474
  disableBroadcastChanges() {
459
- const wasBroadcasting = this._isBroadcasting;
460
- this.changes?.cancel();
461
- const needsDiagnostic = wasBroadcasting && this._isBroadcasting;
462
- this._isBroadcasting = false;
463
- this.dispatchStatus();
464
- if (needsDiagnostic) this.reportDiagnostic({ category: "sync", code: "broadcast-disabled" });
475
+ this.changeRelay.disableBroadcastChanges();
465
476
  }
466
477
  enableBroadcastChanges() {
467
- if (this._isBroadcasting) return;
468
- this._isBroadcasting = true;
469
- this.dispatchStatus();
470
- if (this.changes) {
471
- void this.changes.cancel();
472
- void this.changes.removeAllListeners();
473
- }
474
- this.changes = this.db.changes({
475
- since: "now",
476
- live: true,
477
- include_docs: false,
478
- selector: {
479
- _id: {
480
- $gt: "_local/"
481
- }
482
- }
483
- });
484
- void this.changes.on("change", async (change) => {
485
- this.lastSeq = change.seq;
486
- await this.notifyProgress();
487
- });
488
- const closeChanges = (reason) => {
489
- const wasBroadcasting = this._isBroadcasting;
490
- if (reason) {
491
- if (reason instanceof Error) {
492
- Logger(`Error while broadcasting the changes`, LOG_LEVEL_INFO);
493
- Logger(reason, LOG_LEVEL_VERBOSE);
494
- } else {
495
- Logger(`Broadcasting the changes has been finished`, LOG_LEVEL_INFO);
496
- Logger(reason, LOG_LEVEL_VERBOSE);
497
- }
498
- }
499
- void this.changes?.cancel();
500
- void this.changes?.removeAllListeners();
501
- this.changes = void 0;
502
- this._isBroadcasting = false;
503
- this.dispatchStatus();
504
- if (wasBroadcasting)
505
- this.reportDiagnostic({
506
- category: "sync",
507
- code: "broadcast-disabled",
508
- ...reason instanceof Error ? { reason: "replication-error" } : {}
509
- });
510
- };
511
- void this.changes.on("error", closeChanges);
512
- void this.changes.on("complete", closeChanges);
513
- this.reportDiagnostic({ category: "sync", code: "broadcast-enabled" });
514
- fireAndForget(async () => await this.notifyProgress());
478
+ this.changeRelay.enableBroadcastChanges();
515
479
  }
516
480
  /** Apply automatic broadcast policy without restarting this room. */
517
481
  reconcileAutoBroadcast(enabled) {
@@ -525,89 +489,47 @@ class TrysteroReplicator {
525
489
  get knownAdvertisements() {
526
490
  return this.server?.knownAdvertisements ?? [];
527
491
  }
528
- availableReplicationPairs = /* @__PURE__ */ new Set();
492
+ get availableReplicationPairs() {
493
+ return this.transfers.availableReplicationPairs;
494
+ }
495
+ set availableReplicationPairs(peers) {
496
+ this.transfers.availableReplicationPairs = peers;
497
+ }
529
498
  async sync(remotePeer, showNotice = false, callerSignal) {
530
499
  return await this.runSessionFiniteOperation(
531
- async (signal) => await this.syncWithinSession(remotePeer, showNotice, signal),
500
+ async (signal) => await this.transfers.sync(remotePeer, showNotice, signal),
532
501
  callerSignal
533
502
  );
534
503
  }
535
- async syncWithinSession(remotePeer, showNotice, signal) {
536
- const from = await this.replicateFrom(remotePeer, showNotice, false, false, signal);
537
- if (isP2PReplicationCancelled(from)) return from;
538
- if (from.error) {
539
- Logger("Error while replicating from the remote", LOG_LEVEL_VERBOSE);
540
- Logger(from.error, LOG_LEVEL_VERBOSE);
541
- return from;
542
- }
543
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
544
- const logLevel = showNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
545
- Logger(`P2P Replication has been requested to ${remotePeer}`, logLevel, "p2p-replicator");
546
- const res = await this.requestSynchroniseToPeer(remotePeer, signal);
547
- if (res.ok) {
548
- Logger("P2P Replication has been done", logLevel, "p2p-replicator");
549
- }
550
- if (res.error) {
551
- Logger("Error while syncing from the remote", logLevel, "p2p-replicator");
552
- Logger(res.error, LOG_LEVEL_VERBOSE);
553
- }
554
- return res;
504
+ /** Existing public sets refer to the transfer component's single state owner. */
505
+ get _replicateToPeers() {
506
+ return this.transfers.replicateToPeers;
507
+ }
508
+ set _replicateToPeers(peers) {
509
+ this.transfers.replicateToPeers = peers;
510
+ }
511
+ get _replicateFromPeers() {
512
+ return this.transfers.replicateFromPeers;
513
+ }
514
+ set _replicateFromPeers(peers) {
515
+ this.transfers.replicateFromPeers = peers;
555
516
  }
556
- _replicateToPeers = /* @__PURE__ */ new Set();
557
- _replicateFromPeers = /* @__PURE__ */ new Set();
558
517
  dispatchReplicationProgress(peerId, info) {
559
518
  this.onReplicationProgress(peerId, info);
560
519
  }
561
520
  onReplicationProgress(peerId, info) {
562
- if (this.disposed) {
563
- return false;
564
- }
565
- const name = this.server?._knownAdvertisements?.get(peerId)?.name || peerId;
566
- this._env.events.emitEvent(EVENT_P2P_REPLICATOR_PROGRESS, {
567
- peerId,
568
- peerName: name,
569
- fetching: projectDirectionProgress(info)
570
- });
571
- return true;
521
+ return this.replicationProgress.onReplicationProgress(peerId, info);
572
522
  }
573
523
  onProgressAcknowledged(peerId, info, acknowledgement) {
574
- if (this.disposed) {
575
- return false;
576
- }
577
- if (acknowledgement) {
578
- const next = projectAcknowledgedAttempt(this.acknowledgedAttempts.get(peerId), info, acknowledgement);
579
- if (!next) {
580
- return false;
581
- }
582
- this.acknowledgedAttempts.set(peerId, next);
583
- }
584
- const name = this.server?._knownAdvertisements?.get(peerId)?.name || peerId;
585
- const sending = projectDirectionProgress(info ?? acknowledgement?.finalProgress);
586
- sending.isActive = info != null;
587
- this._env.events.emitEvent(EVENT_P2P_REPLICATOR_PROGRESS, {
588
- peerId,
589
- peerName: name,
590
- sending
591
- });
592
- return true;
524
+ return this.replicationProgress.onProgressAcknowledged(peerId, info, acknowledgement);
593
525
  }
594
- // Sending the progress to the remote peer.
595
- acknowledgeProgress(remotePeerId, info, acknowledgement) {
596
- if (!this.server || this.disposed) return;
597
- try {
598
- const connection = this.server.getConnection(remotePeerId);
599
- void connection.invokeRemoteFunction("onProgressAcknowledged", [this.server.serverPeerId, info, acknowledgement], 500).catch((error) => {
600
- Logger("Error while acknowledging the progress", LOG_LEVEL_VERBOSE);
601
- Logger(error, LOG_LEVEL_VERBOSE);
602
- });
603
- } catch (error) {
604
- Logger("Error while acknowledging the progress", LOG_LEVEL_VERBOSE);
605
- Logger(error, LOG_LEVEL_VERBOSE);
606
- }
526
+ /** Report progress without awaiting the reporting RPC's response. */
527
+ acknowledgeProgress(peerId, info, acknowledgement) {
528
+ this.replicationProgress.acknowledgeProgress(peerId, info, acknowledgement);
607
529
  }
608
530
  async replicateFrom(remotePeer, showNotice = false, fromStart = false, skipOrdinaryReplicationPolicy = false, callerSignal) {
609
531
  return await this.runSessionFiniteOperation(
610
- async (signal) => await this.replicateFromWithinSession(
532
+ async (signal) => await this.transfers.replicateFrom(
611
533
  remotePeer,
612
534
  showNotice,
613
535
  fromStart,
@@ -617,181 +539,8 @@ class TrysteroReplicator {
617
539
  callerSignal
618
540
  );
619
541
  }
620
- async replicateFromWithinSession(remotePeer, showNotice, fromStart, skipOrdinaryReplicationPolicy, signal) {
621
- this.reportDiagnostic({ category: "sync", code: "pull-started", peerId: remotePeer });
622
- try {
623
- const result = await this.pullFromWithinSession(
624
- remotePeer,
625
- showNotice,
626
- fromStart,
627
- skipOrdinaryReplicationPolicy,
628
- signal
629
- );
630
- this.reportDiagnostic(pullResultDiagnostic(remotePeer, result.status));
631
- return result;
632
- } catch (error) {
633
- this.reportDiagnostic(pullFailureDiagnostic(remotePeer, signal?.aborted ?? false));
634
- throw error;
635
- }
636
- }
637
- async pullFromWithinSession(remotePeer, showNotice, fromStart, skipOrdinaryReplicationPolicy, signal) {
638
- if (!skipOrdinaryReplicationPolicy && !await this.canStartOrdinaryReplication(showNotice)) {
639
- return p2pReplicationFailed(new Error("Replication is not ready"));
640
- }
641
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
642
- const logLevel = showNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
643
- const rejection = await this.checkPeerForReplication(remotePeer, logLevel, signal);
644
- if (rejection) return rejection;
645
- Logger(`P2P Replicating from ${remotePeer}`, logLevel, "p2p-replicator");
646
- if (this._replicateFromPeers.has(remotePeer)) {
647
- Logger(`Replication from ${remotePeer} is already in progress`, logLevel, "p2p-replicator");
648
- return p2pReplicationFailed(new Error("Replication from this peer is already in progress"));
649
- }
650
- this._replicateFromPeers.add(remotePeer);
651
- this.dispatchStatus();
652
- const acknowledgement = { attempt: ++nextProgressAttempt };
653
- let latestProgress = {
654
- lastSeq: 0,
655
- maxSeqInBatch: 0,
656
- statistics: { documents: 0, checkedChanges: 0 }
657
- };
658
- this.dispatchReplicationProgress(remotePeer, latestProgress);
659
- this.acknowledgeProgress(remotePeer, latestProgress, acknowledgement);
660
- try {
661
- return await this.transferFromPeer(remotePeer, fromStart, logLevel, signal, (info) => {
662
- latestProgress = info;
663
- this.dispatchReplicationProgress(remotePeer, info);
664
- this.acknowledgeProgress(remotePeer, info, acknowledgement);
665
- });
666
- } catch (e) {
667
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
668
- Logger("Error while P2P replicating", logLevel, "p2p-replicator");
669
- Logger(e, LOG_LEVEL_VERBOSE);
670
- return p2pReplicationFailed(e);
671
- } finally {
672
- this.dispatchReplicationProgress(remotePeer);
673
- this.acknowledgeProgress(remotePeer, void 0, { ...acknowledgement, finalProgress: latestProgress });
674
- this._replicateFromPeers.delete(remotePeer);
675
- this.dispatchStatus();
676
- }
677
- }
678
- async checkPeerForReplication(remotePeer, logLevel, signal) {
679
- Logger(`P2P Requesting Authentication to ${remotePeer}`, logLevel, "p2p-replicator");
680
- const authenticated = signal ? await this.requestAuthenticate(remotePeer, signal) : await this.requestAuthenticate(remotePeer);
681
- if (authenticated !== true) {
682
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
683
- Logger("Peer rejected the connection", logLevel, "p2p-replicator");
684
- return p2pReplicationFailed(new Error("Peer rejected the connection"));
685
- }
686
- let tweaksMatched;
687
- try {
688
- tweaksMatched = signal ? await this.checkTweakValues(remotePeer, signal, logLevel) : await this.checkTweakValues(remotePeer, void 0, logLevel);
689
- } catch (error) {
690
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
691
- throw error;
692
- }
693
- if (tweaksMatched !== true) {
694
- if (signal?.aborted) return P2P_REPLICATION_CANCELLED;
695
- Logger("Tweak values are not matched", logLevel, "p2p-replicator");
696
- return p2pReplicationFailed(new Error("Tweak values are not matched"));
697
- }
698
- return void 0;
699
- }
700
- async transferFromPeer(remotePeer, fromStart, logLevel, signal, onStatistics) {
701
- if (!this.server) {
702
- throw new Error("Server is not available");
703
- }
704
- const connection = this.server.getConnection(remotePeer);
705
- const remoteDB = connection.getRemoteDB(signal);
706
- const pathNormalizationVersion = getPathNormalizationVersion(this.currentSettings);
707
- const [localPathIdentity, remotePathIdentity] = await Promise.all([
708
- readLocalP2PPathIdentity(this.db, pathNormalizationVersion),
709
- readRemoteP2PPathIdentity(remoteDB, pathNormalizationVersion)
710
- ]);
711
- if (localPathIdentity !== pathNormalizationVersion || remotePathIdentity !== pathNormalizationVersion) {
712
- const error = new Error("P2P database path identity does not match the configured path identity.");
713
- Logger(error.message, logLevel, "p2p-replicator");
714
- return p2pReplicationFailed(error);
715
- }
716
- Logger(`P2P replicateFrom preparing remote DB info for ${remotePeer}`, LOG_LEVEL_VERBOSE, "p2p-replicator");
717
- const remoteDBInfo = await remoteDB.info();
718
- Logger(
719
- `P2P replicateFrom remote DB info for ${remotePeer}: ${remoteDBInfo.db_name} seq=${remoteDBInfo.update_seq}`,
720
- LOG_LEVEL_VERBOSE,
721
- "p2p-replicator"
722
- );
723
- const localDBInfo = await this.db.info();
724
- Logger(
725
- `P2P replicateFrom local DB info for ${remotePeer}: ${localDBInfo.db_name} seq=${localDBInfo.update_seq}`,
726
- LOG_LEVEL_VERBOSE,
727
- "p2p-replicator"
728
- );
729
- Logger(`P2P replicateFrom entering replicateShim for ${remotePeer}`, LOG_LEVEL_VERBOSE, "p2p-replicator");
730
- const outcome = await replicateShim(
731
- this.db,
732
- remoteDB,
733
- async (docs, info) => {
734
- await this._env.processReplicatedDocs(docs);
735
- void this.notifyProgress(remotePeer);
736
- Logger(
737
- `P2P Replication from ${remotePeer}
738
- ${info.lastSeq} / ${info.maxSeqInBatch})`,
739
- logLevel,
740
- "p2p-replicator"
741
- );
742
- },
743
- {
744
- live: false,
745
- rewind: fromStart,
746
- signal,
747
- onStatistics
748
- }
749
- );
750
- Logger(`P2P replicateFrom replicateShim returned for ${remotePeer}`, LOG_LEVEL_VERBOSE, "p2p-replicator");
751
- if (outcome.status === "cancelled") {
752
- Logger(`P2P Replication from ${remotePeer} has been cancelled`, logLevel, "p2p-replicator");
753
- return P2P_REPLICATION_CANCELLED;
754
- }
755
- Logger(`P2P Replication from ${remotePeer} has been completed`, logLevel, "p2p-replicator");
756
- return P2P_REPLICATION_COMPLETED;
757
- }
758
542
  notifyProgress(excludePeerId) {
759
- if (!this._isBroadcasting) {
760
- return;
761
- }
762
- if (!this.server) {
763
- return;
764
- }
765
- for (const peer of this.server.knownAdvertisements) {
766
- const peerId = peer.peerId;
767
- if (peerId === excludePeerId) {
768
- continue;
769
- }
770
- void serialized(`notifyProgress-${peerId}`, () => this.notifyPeerProgress(peerId));
771
- }
772
- return Promise.resolve();
773
- }
774
- async notifyPeerProgress(peerId) {
775
- const isAcceptable = await this.server?.isAcceptablePeer(peerId);
776
- if (!isAcceptable) {
777
- this.reportDiagnostic({
778
- category: "sync",
779
- code: "change-notification-ignored",
780
- peerId,
781
- reason: "not-accepted"
782
- });
783
- Logger(`Peer ${peerId} is not acceptable to notify progress`, LOG_LEVEL_VERBOSE);
784
- return;
785
- }
786
- try {
787
- const result = await this.server?.getConnection(peerId).invokeRemoteFunction("onProgress", [this.server?.serverPeerId], 0);
788
- this.reportDiagnostic({ category: "sync", code: "change-notification-sent", peerId });
789
- return result;
790
- } catch (error) {
791
- this.reportDiagnostic(notificationFailureDiagnostic(peerId, error));
792
- Logger(`Error while notifying progress to ${peerId}`, LOG_LEVEL_VERBOSE);
793
- Logger(error, LOG_LEVEL_VERBOSE);
794
- }
543
+ return this.changeRelay.notifyProgress(excludePeerId);
795
544
  }
796
545
  async requestBroadcastChanges(peerId) {
797
546
  return await this.server?.getConnection(peerId).invokeRemoteFunction("requestBroadcasting", [this.server.serverPeerId], 0);
@@ -804,225 +553,43 @@ ${info.lastSeq} / ${info.maxSeqInBatch})`,
804
553
  Logger(e, LOG_LEVEL_VERBOSE);
805
554
  }
806
555
  }
807
- _watchingPeers = /* @__PURE__ */ new Set();
556
+ get _watchingPeers() {
557
+ return this.changeRelay.watchingPeers;
558
+ }
559
+ set _watchingPeers(peers) {
560
+ this.changeRelay.watchingPeers = peers;
561
+ }
808
562
  watchPeer(peerId) {
809
- if (!this._watchingPeers.has(peerId)) {
810
- this.reportDiagnostic({ category: "sync", code: "watch-enabled", peerId });
811
- }
812
- this._watchingPeers.add(peerId);
813
- this.dispatchStatus();
563
+ this.changeRelay.watchPeer(peerId);
814
564
  }
815
565
  unwatchPeer(peerId) {
816
- if (this._watchingPeers.has(peerId)) {
817
- this.reportDiagnostic({ category: "sync", code: "watch-disabled", peerId });
818
- }
819
- this._watchingPeers.delete(peerId);
820
- this.dispatchStatus();
566
+ this.changeRelay.unwatchPeer(peerId);
821
567
  }
822
568
  async onUpdateDatabase(fromPeerId) {
823
- if (this._watchingPeers.has(fromPeerId)) {
824
- this.reportDiagnostic({ category: "sync", code: "change-notification-received", peerId: fromPeerId });
825
- Logger(`Progress notification from ${fromPeerId}`, LOG_LEVEL_VERBOSE);
826
- return await serialized(`onProgress-${fromPeerId}`, async () => {
827
- return await this.runFiniteReplicationActivity(() => this.replicateFrom(fromPeerId));
828
- });
829
- }
830
- this.reportDiagnostic({
831
- category: "sync",
832
- code: "change-notification-ignored",
833
- peerId: fromPeerId,
834
- reason: "not-watching"
835
- });
836
- return false;
569
+ return await this.changeRelay.onUpdateDatabase(fromPeerId);
837
570
  }
571
+ /** Fetch and validate shared settings; applying them remains the caller's responsibility. */
838
572
  async getRemoteConfig(peerId) {
839
- if (!this.server) {
840
- Logger("Server is not available", LOG_LEVEL_NOTICE);
841
- return false;
842
- }
843
- const connection = this.server.getConnection(peerId);
844
- const encryptedConfig = await connection.invokeRemoteFunction("getAllConfig", [this.server.serverPeerId], 0);
845
- const passphrase = await this.confirm.askString(
846
- "Passphrase required",
847
- this.translate("P2P.AskPassphraseForDecrypt"),
848
- "something you only know",
849
- true
850
- );
851
- if (!passphrase || passphrase.trim() == "") {
852
- Logger(
853
- "Passphrase is required to decrypt the configuration. The config cannot be decrypted",
854
- LOG_LEVEL_NOTICE
855
- );
856
- return false;
857
- }
858
- try {
859
- const decryptedConfig = JSON.parse(
860
- await decrypt(encryptedConfig, passphrase)
861
- );
862
- const settings = {
863
- ...decryptedConfig,
864
- idDerivationVersion: decryptedConfig.idDerivationVersion ?? 0,
865
- idDerivationKey: decryptedConfig.idDerivationKey ?? ""
866
- };
867
- configuredIdKey(settings);
868
- return omitP2PRuntimeSettings(settings);
869
- } catch (e) {
870
- Logger("Error while decrypting the configuration", LOG_LEVEL_NOTICE);
871
- Logger(e, LOG_LEVEL_VERBOSE);
872
- return false;
873
- }
573
+ return await this.configurationExchange.getRemoteConfig(peerId);
874
574
  }
875
- /** Compare peer settings without exceeding the presentation authority of the initiating call. */
575
+ /** Compare peer settings without exceeding the initiating call's presentation authority. */
876
576
  async checkTweakValues(peerId, signal, logLevel = LOG_LEVEL_NOTICE) {
877
- if (!this.server) {
878
- Logger("Server is not available", logLevel);
879
- return false;
880
- }
881
- const peerPlatform = this.server.knownAdvertisements.find((e) => e.peerId == peerId)?.platform;
882
- if (peerPlatform == null) {
883
- Logger("Peer is not found", logLevel);
884
- return false;
885
- }
886
- const connection = this.server.getConnection(peerId);
887
- const challengeBytes = new Uint8Array(16);
888
- (await getWebCrypto()).getRandomValues(challengeBytes);
889
- const challenge = uint8ArrayToHexString(challengeBytes);
890
- const tweakValues = await connection.invokeRemoteObjectFunction("getTweakSettings", [challenge], 5e3, signal);
891
- if (signal?.aborted) return false;
892
- const thisTweakValues = await this.getTweakSettings(challenge);
893
- const localPathNormalizationVersion = getPathNormalizationVersion(thisTweakValues);
894
- const peerPathNormalizationVersion = getPathNormalizationVersion(tweakValues);
895
- if (localPathNormalizationVersion !== peerPathNormalizationVersion) {
896
- Logger("Replication cancelled: The path identity mode does not match this peer.", logLevel);
897
- return false;
898
- }
899
- if (this.platform === "pseudo-replicator" || peerPlatform === "pseudo-replicator") {
900
- return true;
901
- }
902
- if (thisTweakValues.passphrase !== tweakValues.passphrase) {
903
- Logger(
904
- "Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.",
905
- logLevel
906
- );
907
- return false;
908
- }
909
- if (thisTweakValues.encrypt !== tweakValues.encrypt || thisTweakValues.usePathObfuscation !== tweakValues.usePathObfuscation) {
910
- Logger(
911
- "Replication cancelled: The encryption or path obfuscation settings do not match this peer.",
912
- logLevel
913
- );
914
- return false;
915
- }
916
- if (thisTweakValues.encrypt && thisTweakValues.usePathObfuscation && ((thisTweakValues.idDerivationVersion ?? 0) !== (tweakValues.idDerivationVersion ?? 0) || (thisTweakValues.idDerivationProof ?? "") !== (tweakValues.idDerivationProof ?? ""))) {
917
- Logger("Replication cancelled: The ID derivation settings do not match this peer.", logLevel);
918
- return false;
919
- }
920
- const tweakAssessment = assessTweakCompatibility(thisTweakValues, tweakValues);
921
- if (!tweakAssessment.representationDiffers) return true;
922
- Logger(
923
- "Some mismatched configuration have been detected... Please check settings for efficient replication.",
924
- logLevel
925
- );
926
- return true;
927
- }
928
- configuredPeerNames() {
929
- return [...new Set(this.currentSettings.P2P_SyncOnReplication.split(",").map((name) => name.trim()))].filter(
930
- Boolean
931
- );
577
+ return await this.peerAgreement.checkTweakValues(peerId, signal, logLevel);
932
578
  }
933
- findAdvertisement(peerName) {
934
- return this.knownAdvertisements.find((advertisement) => advertisement.name === peerName);
935
- }
936
- async waitForConfiguredAdvertisements(peerNames, timeoutMs, signal) {
937
- const allPresent = () => peerNames.every((name) => this.findAdvertisement(name) !== void 0);
938
- if (allPresent() || timeoutMs <= 0 || signal?.aborted) return;
939
- await new Promise((resolve) => {
940
- let timeout;
941
- let detachAdvertisement = () => void 0;
942
- const finish = () => {
943
- detachAdvertisement();
944
- signal?.removeEventListener("abort", finish);
945
- if (timeout !== void 0) compatGlobal.clearTimeout(timeout);
946
- resolve();
947
- };
948
- detachAdvertisement = this._env.events.onEvent(EVENT_ADVERTISEMENT_RECEIVED, () => {
949
- if (allPresent()) finish();
950
- });
951
- signal?.addEventListener("abort", finish, { once: true });
952
- timeout = compatGlobal.setTimeout(finish, timeoutMs);
953
- if (allPresent() || signal?.aborted) finish();
954
- });
955
- }
956
- configuredTargetResult(name, peerId, result) {
957
- if (result.status === "completed") return { name, peerId, status: "completed" };
958
- if (result.status === "cancelled") return { name, peerId, status: "cancelled" };
959
- return { name, peerId, status: "failed", error: result.error };
960
- }
961
- /** Synchronise configured peer targets without opening peer-selection UI. */
579
+ /** Synchronise configured targets through their own discovery and aggregation workflow. */
962
580
  async replicateFromCommand(showResult = false, discoveryTimeoutMs = 5e3, callerSignal) {
963
- const logLevel = showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
964
- if (!this.currentSettings.P2P_Enabled) {
965
- Logger(this.translate("P2P.NotEnabled"), logLevel);
966
- return { status: "blocked", reason: "no-targets", targets: [] };
967
- }
968
- const peerNames = this.configuredPeerNames();
969
- if (peerNames.length === 0) {
970
- Logger(this.translate("P2P.NoAutoSyncPeers"), logLevel);
971
- return { status: "blocked", reason: "no-targets", targets: [] };
972
- }
973
- await this.waitForConfiguredAdvertisements(peerNames, discoveryTimeoutMs, callerSignal);
974
- const targets = [];
975
- for (const peerName of peerNames) {
976
- if (callerSignal?.aborted) {
977
- targets.push({ name: peerName, status: "cancelled" });
978
- continue;
979
- }
980
- const advertisement = this.findAdvertisement(peerName);
981
- if (!advertisement) {
982
- Logger(this.translate(`P2P.SeemsOffline`, { name: peerName }), logLevel);
983
- targets.push({ name: peerName, status: "missing" });
984
- continue;
985
- }
986
- const acceptance = await this.server?.evaluatePeerAcceptance(advertisement.peerId) ?? "unknown";
987
- if (acceptance !== "accepted") {
988
- targets.push({
989
- name: peerName,
990
- peerId: advertisement.peerId,
991
- status: acceptance === "rejected" ? "rejected" : acceptance === "undecided" ? "undecided" : "missing"
992
- });
993
- continue;
994
- }
995
- Logger(this.translate(`P2P.SyncStartedWith`, { name: peerName }), logLevel);
996
- const result = await this.automationCoordinator.runBaseline(
997
- peerName,
998
- () => this.sync(advertisement.peerId, showResult, callerSignal)
999
- );
1000
- targets.push(this.configuredTargetResult(peerName, advertisement.peerId, result));
1001
- }
1002
- if (targets.every((target) => target.status === "completed")) {
1003
- Logger(this.translate("P2P.SyncCompleted"), logLevel);
1004
- return { status: "completed", targets };
1005
- }
1006
- if (targets.every((target) => target.status === "cancelled")) {
1007
- return { status: "cancelled", targets };
1008
- }
1009
- return { status: "partial", targets };
581
+ return await this.configuredTargets.replicateFromCommand(showResult, discoveryTimeoutMs, callerSignal);
1010
582
  }
583
+ /** Stop the current relay snapshot and retain the public asynchronous host-stop dispatch. */
1011
584
  disconnectFromServer() {
1012
- const connections = getRelaySockets();
1013
- const sockets = Object.entries(connections);
1014
- pauseRelayReconnection();
1015
- sockets.forEach(([, s]) => {
1016
- s.close();
1017
- });
1018
- void this.pauseServe();
585
+ disconnectRelay({ relay: this.relayControl, pauseServe: () => this.pauseServe() });
1019
586
  }
1020
587
  async pauseServe() {
1021
588
  await this.server?.close();
1022
589
  await this.server?.dispatchConnectionStatus();
1023
590
  }
1024
591
  allowReconnection() {
1025
- resumeRelayReconnection();
592
+ this.relayControl.resumeReconnection();
1026
593
  }
1027
594
  }
1028
595
  export {